I have a list-column and I would like to use c()
for each group to combine these lists in summarize
. This should result in one row per group, but it does not (note the code was written using dplyr >= 1.1.0):
library(dplyr)
df <- tibble::tibble(group = c("A", "A", "B"),
list_col = list(list("One"), list("Two"), list("Three")))
df |>
summarize(list_col = c(list_col),
.by = group)
This returns:
group list_col
<chr> <list>
1 A <list [1]>
2 A <list [1]>
3 B <list [1]>
Warning message:
Returning more (or less) than 1 row per `summarise()` group was deprecated in dplyr 1.1.0.
i Please use `reframe()` instead.
i When switching from `summarise()` to `reframe()`, remember that `reframe()` always
returns an ungrouped data frame and adjust accordingly.
Call `lifecycle::last_lifecycle_warnings()` to see where this warning was generated.
Expected Output
output <- tibble::tibble(group = c("A", "B"),
list_col = list(list("One", "Two"), list("Three")))
group list_col
<chr> <list>
1 A <list [2]>
2 B <list [1]>
output$list_col[[1]]
[[1]]
[1] "One"
[[2]]
[1] "Two"
Alternate Solution
You could do something like the following code. However A) it changes the row-wise type of the column and B) I would like to specifically know why c()
does not work:
df |>
summarize(list_col = list(unlist(list_col)),
.by = group)
group list_col
<chr> <list>
1 A <chr [2]>
2 B <chr [1]>
Within the first group (A
) I expected something like the following to happen to combine the two lists into one list:
c(list("One"), list("Two"))
[[1]]
[1] "One"
[[2]]
[1] "Two"
So, why does this not work? Is this a bug or is there something with the syntax I am missing?