Is there a more tidyverse
-idiomatic way to combine several columns into a list column than using mapply
?
For example given the following
tibble(.rows = 9) %>%
mutate(foo = runif(n()),
a_1 = runif(n()),
a_2 = runif(n()),
a_3 = runif(n())) ->
Z
(where Z
might contain other columns, and might also contain more than 3 a
s) one can do
Z %>% mutate(A = mapply(c, a_1, a_2, a_3, SIMPLIFY = FALSE))
which works fine, although it would be nice to be able to say starts_with('a_')
instead of a_1, a_2, a_3
.
Another possibility is
Z %>%
rowid_to_column() %>%
pivot_longer(cols = starts_with('a_')) %>%
group_by(rowid) %>%
summarise(foo = unique(foo),
A = list(value)) %>%
select(-rowid)
which technically works, but introduces other problems (e.g., it uses an ugly foo = unique(foo)
; furthermore if instead of just one foo
there were many foo
s it would become a bit more involved).