R 中所有组合 1 到 n_1、2 到 n_2、...、n 到 n_n 作为列表中的向量?

问题描述 投票:0回答:1

我正在寻找基于 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

那么,有没有更有效的方法来实现这一目标?

r combinatorics
1个回答
0
投票

这个怎么样?

split(
    unlist(expand.grid(lapply(n, seq_len)), use.names = FALSE),
    rep(seq_len(prod(n)), length(n))
)

但我想它只是更短,但实际上达到了与你相同的效果

© www.soinside.com 2019 - 2024. All rights reserved.