我正在寻找最有效的方法来创建基于R中n个不同系列的组合.
Base R有一个名为expand.grid的很好的函数,它将所有组合作为一个数据框返回,但我需要将每个组合作为向量作为单独的列表元素.
因此,从那时起,实现我想要的东西应该不是一项困难的任务,但我首先需要创建一个数据框这一事实似乎是这个过程中不必要的一步.
举个例子:让我们假设我想要所有的组合,其中第一个元素是1,2,3或4,第二个是1或2,第三个是1,2或3.输入应该是序列中的最大整数:
library(dplyr)
c(4,2,3) %>% #This is the input; the length can be anything, here it happens to be 3
lapply(\(elem) seq(elem)) %>% #Here we create the sequences: 1,2,3,4 & 1,2 & 1,2,3
expand.grid %>% #A data frame with all the possible combinations
{split(unlist(.),seq(nrow(.)))} #We unlist the whole data frame into one vector, and split it into 1,2,...,nrow(data frame) equally sized vectors, which ultimately become list elements
那么,有没有更有效的方法来实现这一点呢?