stevec
stevec

Reputation: 52308

Combine multiple list columns into one list column in R?

When working with a data.frame containing columns of lists, how can multiple columns of lists be combined so that their rowwise contents are combined into a single column of lists?

Example

Here's a two-column data.frame (both columns are columns of lists)

df <- structure(list(foo = list(c("foo1", "foo1.1"), "foo2", 
    "foo3"), bar = list("bar1", 
    "bar2", "bar3")), row.names = c(NA, 
-3L), class = c("tbl_df", "tbl", "data.frame"))

How can we make a third column which is also a column of lists, but where each row contains the contents of the lists in the other two columns?

e.g. The first row would contain the 2 items in df[1, 1]$foo and the single item in df[1,2]$bar; that is, these three items in one list foo1 foo1.1 bar (and of course the same for the second row, third row and so on)

Note: I suspect the solution may involve purrr, however I am not certain

Upvotes: 3

Views: 4974

Answers (2)

tmfmnk
tmfmnk

Reputation: 39858

With dplyr, you can do:

df %>%
 mutate(foo_bar = mapply(c, foo, bar))

  foo       bar       foo_bar  
  <list>    <list>    <list>   
1 <chr [2]> <chr [1]> <chr [3]>
2 <chr [1]> <chr [1]> <chr [2]>
3 <chr [1]> <chr [1]> <chr [2]>

Or with the addition of purrr:

df %>%
 mutate(foo_bar = map2(foo, bar, c))

With multiple columns:

df %>%
 mutate(bar2 = bar) %>%
 mutate(res = pmap(across(everything()), c))

  foo       bar       bar2      res      
  <list>    <list>    <list>    <list>   
1 <chr [2]> <chr [1]> <chr [1]> <chr [4]>
2 <chr [1]> <chr [1]> <chr [1]> <chr [3]>
3 <chr [1]> <chr [1]> <chr [1]> <chr [3]>

Upvotes: 5

akrun
akrun

Reputation: 887138

In base R, we can use Map

df$foo_bar <-  do.call(Map, c(f = c, df))

Upvotes: 1

Related Questions