【发布时间】:2016-06-30 21:48:52
【问题描述】:
是否可以在 R 中使用 expand.grid() 在 y 集合中创建 x 因子的所有可能组合?
例如,我有 12 个因素:
Factor1 = c("1", "2", "3", "4"), #Fixed Attribute: 4 lvls
Factor2 = c("5", "6", "7", "8", "9"), #Fixed Attribute: 5 lvls
Factor3 = c("10", "11", "12","13"), #Fixed Attribute: 4 lvls
Factor4 = c("14", "15", "16"), #Fixed Attribute: 4 lvls
Factor5 = c("17", "18", "19", "20", "21"), #Variable Attribute: 5 lvls
Factor6 = c("22", "23"), #Variable Attribute: 2 lvls
Factor7 = c("24", "25", "26"), #Variable Attribute: 3 lvls
Factor8 = c("27", "28", "29") #Variable Attribute: 3 lvls
Factor9 = c("30", "31", "32", "33"), #Variable Attribute: 4 lvls
Factor10= c("34", "35"), #Variable Attribute: 2 lvls
Factor11 = c("36", "37", "38"), #Variable Attribute: 3 lvls
Factor12 = c("39", "40", "41") #Variable Attribute: 3 lvls
我希望始终在expand.grid() 中包含前 4 个(即它们是固定的),并在所有可能的 4 个集合中循环到最后 8 个,这等于 70 个唯一集合。然后附加所有生成的 70 个数据帧。
我可以通过创建 70 个不同的 expand.grid() 代码块来以蛮力的方式实现这一点,但是有没有一种技术上不太优雅的方式来做到这一点?
例如暴力破解方式如下:
expand.grid(Factor1, Factor2,Factor3,Factor4,Factor5,Factor6,Factor7,Factor8)
expand.grid(Factor1, Factor2,Factor3,Factor4,Factor5,Factor6,Factor7,Factor9)
expand.grid(Factor1, Factor2,Factor3,Factor4,Factor5,Factor6,Factor7,Factor10)
expand.grid(Factor1, Factor2,Factor3,Factor4,Factor5,Factor6,Factor7,Factor11)
expand.grid(Factor1, Factor2,Factor3,Factor4,Factor5,Factor6,Factor7,Factor12)
....etc...
所以我最终会得到 70 个不同的数据框,因为有 70 种独特的方法可以从因子 4-12 中选择 4 个因子(即,有 70 种方法可以从 8 个列表中选择 4 个项目)
此外,生成的数据框可能是 150 万行。这会导致内存问题吗?
谢谢,
【问题讨论】:
-
你能分享一下预期的输出吗?
-
嗨@ChirayuChamoli,我已经添加了一个示例,说明我将如何通过蛮力做到这一点。请让我知道这是否足够澄清。
标签: r dataframe combinatorics