【问题标题】:r: create data frame with all possible options and number of variable combinationsr:创建具有所有可能选项和变量组合数量的数据框
【发布时间】:2017-07-18 08:53:36
【问题描述】:

这个问题可能很明显或已经问过,但我找不到解决方案:

我想创建一个包含所有可能组合(和变量数量)的数据框,使其看起来像以下示例:

dataframe <- data.frame(variable =   1:4, 
                        a = c("gender", NA, NA, NA),
                        b = c("age", NA, NA, NA),
                        c = c("city", NA, NA, NA),
                        d = c("education", NA, NA, NA),
                        e = c("gender", "age", NA, NA),
                        f = c("gender", "city", NA, NA), 
                        g = c("gender", "education", NA, NA), 
                        h = c("age", "city", NA, NA), 
                        i = c("age", "education", NA, NA), 
                        j = c("city", "education", NA, NA), 
                        k = c("gender", "age", "city", NA), 
                        l = c("gender", "age", "education", NA), 
                        m = c("gender", "city", "education", NA),
                        n = c("gender", "age", "city", "education"))

我有太多变量,所以不值得写出来,我想避免错误。感谢您的帮助!

【问题讨论】:

  • 你能显示用于创建这个的输入数据吗
  • 输入数据可能是任何数据框的 15 个列名。或者只是variables = c("gender", "age", "city", "education", "school", "income", "bmi", "SES", "..."),或者你需要什么输入数据?计算出来的数据框当然必须有与变量一样多的行。
  • 当心组合爆炸。使用 15 个变量,您可以获得 2 ^ 15 列
  • 您的用例是什么?如果它尝试不同的模型,还有更好的选择:Lasso、Ridge、stepwise 等等
  • @Aurèle 好点。我想根据推理查看多元回归的不同组合,而不使用模型选择函数。我只是想看看可能的组合来尝试不同的回归模型。

标签: r variables dataframe combinations


【解决方案1】:

这是combn 的选项。获取变量名的vector,遍历vector的序列,在vector上应用combnm指定为循环中的序列,转换为data.framecbind所有list 元素在一起。来自rowrcbind.fill 适用于fillNA 用于行数少于最大行数的list 元素data.frame

library(rowr)
res <- do.call(cbind.fill, c(fill = NA, lapply(seq_along(v1), function(i) {
       m1 <- combn(v1, i)
       if(is.vector(m1)) as.data.frame.list(m1)  else as.data.frame(m1)})))
colnames(res) <- letters[seq_along(res)]

或者正如@Moody_Mudskipper 建议的那样,

res1 <- do.call(cbind.fill, c(fill = NA, lapply(seq_along(v1), function(i) combn(v1, i))))
colnames(res1) <- letters[seq_len(ncol(res1))]

数据

v1 <- c('gender', 'age', 'city', 'education')

【讨论】:

  • 谢谢你,@akrun
  • @akrun 为什么在第 4 行出现这些条件?对我来说,这样做效果很好:lapply(seq_along(v1),combn,x=v1) %&gt;% {do.call(cbind.fill,c(.,fill=NA))} %&gt;% setNames(letters[1:ncol(.)])
  • @Moody_Mudskipper 因为combn(v1, 1) 给出了一个向量。我不确定你是否得到相同的输出
  • @Moody_Mudskipper 谢谢,看起来像你建议的那样工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-26
  • 2021-07-10
  • 2021-02-17
  • 1970-01-01
相关资源
最近更新 更多