字符向量组合列表

时间:2015-11-02 01:29:25

标签: r combinations

我试图采用名称为四种可能模型的矢量" x1"," x2"," x3"," X4"并创建这些术语的所有可能排列的更长向量,这样我就可以开始一个具有每个属性的数据框。

下面的代码看起来应该有效,但不是。这些元素不会被粘贴在一起,例如" x1"和" x2"组合应该导致" x1x2"型号名称,但它保持" x1" " X 2"

models <- c("x1","x2","x3","x4")

modelist<- as.character()
for(i in 1:4){
  modelist <- c(modelist,combn(models,m=i,FUN=paste0,simplify = T))
}
modelist

由于我没有寻找互动条款,x1x1不应该出现,但我有兴趣知道如何做到这一点以供将来参考。

这是我正在寻找的输出:

modelist <- c("x1","x2","x3","x4","x1x2","x1x3","x1x4","x2x3","x2x4","x3x4",
            "x1x2x3","x2x3x4","x1x2x4","x1x3x4","x1x2x3x4")

那应该包含在模型师中的内容。

1 个答案:

答案 0 :(得分:5)

paste()及其默认参数以及sep = ""将无效,因为combn()的结果也是原子向量,但对于每个组合。因此,对于每种组合,它基本上与以下相同。

paste(letters[1:4])
# [1] "a" "b" "c" "d"
paste(letters[1:4], sep = "")
# [1] "a" "b" "c" "d"
paste(letters[1:4], collapse = "")
# [1] "abcd"

因此,您需要在collapse = ""中使用paste()。这是lapply()解决方案。

unlist(lapply(1:4, function(i) combn(models, i, paste, collapse = "")))
#  [1] "x1"       "x2"       "x3"       "x4"       "x1x2"     "x1x3"     "x1x4"
#  [8] "x2x3"     "x2x4"     "x3x4"     "x1x2x3"   "x1x2x4"   "x1x3x4"   "x2x3x4"
# [15] "x1x2x3x4"

如果你想继续使用for()循环,我建议你分配一个列表,而不是在循环中构建字符向量。效率更高。你可以分配一个长度为sum(choose(4, 1:4))的字符向量,但是循环索引有点棘手,并且列表的排除比担心所有这些要容易得多。此外,列表是处理不同长度的类似对象时使用的标准结构。

modlist <- vector("list", 4)
for(i in 1:4) {
    modlist[[i]] <- combn(models, i, paste, collapse = "")
}
unlist(modlist)
#  [1] "x1"       "x2"       "x3"       "x4"       "x1x2"     "x1x3"     "x1x4"
#  [8] "x2x3"     "x2x4"     "x3x4"     "x1x2x3"   "x1x2x4"   "x1x3x4"   "x2x3x4"
# [15] "x1x2x3x4"