累积R中每个可能组合的值

假设我有数据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
  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

回答

data.table使用Reduce+的选项outer

setDT(test)[
  ,
  dummy := .(Reduce(function(x, y) outer(x, y, paste),
    items,
    accumulate = TRUE
  )),
  ID
]

> test
   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


回答

另一种方法expand.grid()

test %>% group_by(ID) %>%
mutate(dummy = accumulate(items, ~do.call("paste",expand.grid(.x, .y)))) %>% 
data.frame()

给,


回答

您可以使用外积来粘贴两个向量来做到这一点......

test2 <- test %>% group_by(ID) %>%
  mutate(dummy = accumulate(items, ~outer(.x, .y, paste)))

str(test2)
grouped_df[,3] [5 x 3] (S3: grouped_df/tbl_df/tbl/data.frame)
 $ items:List of 5
  ..$ : chr "a"
  ..$ : chr [1:2] "b" "c"
  ..$ : chr [1:2] "d" "e"
  ..$ : chr "f"
  ..$ : chr [1:2] "g" "h"
 $ ID   : num [1:5] 1 1 1 2 2
 $ dummy:List of 5
  ..$ : chr "a"
  ..$ : chr [1, 1:2] "a b" "a c"
  ..$ : chr [1, 1:2, 1:2] "a b d" "a c d" "a b e" "a c e"
  ..$ : chr "f"
  ..$ : chr [1, 1:2] "f g" "f h"


回答

如果你想要所有可能的组合使用sapplyover.x

library(dplyr)
library(purrr)

test %>% 
  group_by(ID) %>%
  mutate(dummy = accumulate(items, ~c(sapply(.x, paste, .y)))) %>%
  pull(dummy)

#[[1]]
#[1] "a"

#[[2]]
#[1] "a b" "a c"

#[[3]]
#[1] "a b d" "a b e" "a c d" "a c e"

#[[4]]
#[1] "f"

#[[5]]
#[1] "f g" "f h"


以上是累积R中每个可能组合的值的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>