假设我有数据test
(给定的 dput)其中 list-col 说items
:
test <- structure(list(items = list('a', c('b', 'c'), c('d', 'e'), 'f', c('g', 'h')),
ID = c(1,1,1,2,2)), row.names = c(NA, 5L), class = "data.frame")
library(tidyverse)
test %>% group_by(ID) %>%
mutate(dummy = accumulate(items, ~paste(.x, .y)))
我得到这样的 list-col 输出
items ID dummy
1 a 1 a
2 b, c 1 a b, a c
3 d, e 1 a b d, a c e
4 f 2 f
5 g, h 2 f g, f h
我希望 row3 中有四个项目,具有每种可能的组合,即c("a b d", "a b e", "a c d", "a c e")
。然而,这些是否是列表中的单独项目并不重要。换句话说,dummy 的输出可能是多级列表类型,其中 row3 将包含列表中的四个项目。我尝试使用expand.grid
,但我在某个地方做错了什么!
所以我想要的输出看起来像
items ID dummy
1 a 1 a
2 b, c 1 a b, a c
3 d, e 1 a b d, a c d, a b e, a c e
4 f 2 f
5 g, h 2 f g, f h