How to map over a list of lists in dataframe in R? (tidyverse pipeline)

Viewed 974

I'm trying to add the elements of an integer vector, which are nested in a two-level list.

I came up with this solution, but I think it's a little uncommon, so I am looking for another alternative:

df <- tibble(
  a = list(list(c(1, 2), c(3, 4)), list(c(1, 2), c(3, 4)))
)

df %>% 
  mutate(
   b = a %>% modify_depth(2, sum) %>% map(unlist)
  )

which gives, and it's the right solution. But I am looking to use more of a map solution and less of modify.

# A tibble: 2 x 2
  a          b        
  <list>     <list>   
1 <list [2]> <dbl [2]>
2 <list [2]> <dbl [2]>

Solution in view mode:

enter image description here

1 Answers

If we don't know the depth and the list elements have multiple depths or same depth, rrapply would be more general

libary(dplyr)
library(purrr)
df %>%
    mutate(b = rrapply::rrapply(a, f = sum) %>%
                   map(unlist))

-output

# A tibble: 2 x 2
#  a          b        
#  <list>     <list>   
#1 <list [2]> <dbl [2]>
#2 <list [2]> <dbl [2]>

also, there is map_depth. According to ?map_depth

map_depth() allows to apply .f to a specific depth level of a nested vector

which is same as modify_depth

df %>% 
  mutate(
      b = a %>% 
              map_depth(2, sum) %>% 
              map(unlist) )
Related