累积 R 中每个可能组合的值 [英] Accumulate values for every possible combination in R

查看:37
本文介绍了累积 R 中每个可能组合的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有数据 test(给出的 dput),其中列表列表示 items:

Let's say I have data test (dput given) where a list-col say 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 输出

I am getting an output with list-col like this

  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

我希望第 3 行有四个项目,具有每种可能的组合,即 c(ab d", ab e", ac d", ac e").然而,这些是否是列表中的单独项目并不重要.换句话说,dummy 的输出可能是多级列表类型,其中 row3 将包含列表中的四个项目.我尝试使用 expand.grid,但我在某处做错了!

I would like there to be four items in row3, having each possible combination, i.e. c("a b d", "a b e", "a c d", "a c e"). It however doesn't matter if these are separate items in the list or not. In other words, the output of dummy may be of type multi-level list, where row3 will contain four items in the list. I tried using expand.grid, but I am doing something wrong somewhere!

所以我想要的输出看起来像

So my desired output will look like

  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

推荐答案

如果你想要所有可能的组合,请使用 sapply 而不是 .x

If you want every possible combination use sapply over .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 中每个可能组合的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆