【问题标题】:How to make a unique combination of vectors in R?如何在R中制作独特的向量组合?
【发布时间】:2014-01-28 15:27:27
【问题描述】:

我有几个由三个名称组成的向量。我想获得这些向量的所有独特的成对组合。例如,使用其中两个向量,我可以得到非唯一组合

sham1 <- c('a', 'b')
sham2 <- c('d', 'e')
shams <- list(sham1, sham2) 
combinations <- apply(expand.grid(shams, shams),1, unname)

给出以下组合

> dput(combinations)
list(
list(c("a", "b"), c("a", "b")), 
list(c("d", "e"), c("a", "b")), 
list(c("a", "b"), c("d", "e")), 
list(c("d", "e"), c("d", "e"))
)

我尝试使用unique(combinations),但这给出了相同的结果。我想得到的是

> dput(combinations)
list(
list(c("a", "b"), c("a", "b")), 
list(c("d", "e"), c("a", "b")), 
list(c("d", "e"), c("d", "e"))
)

因为已经有list(c("d", "e"), c("a", "b"))的组合,我不需要list(c("a", "b"), c("d", "e"))的组合 怎样才能只得到向量的唯一组合?

【问题讨论】:

    标签: r unique combinations


    【解决方案1】:
    s <- seq(length(shams))
    # get unique pairs of shams indexes, including each index with itself.
    uniq.pairs <- unique(as.data.frame(t(apply(expand.grid(s, s), 1, sort))))
    #   V1 V2
    # 1  1  1
    # 2  1  2
    # 4  2  2
    result <- apply(uniq.pairs, 1, function(x) shams[x])
    

    【讨论】:

      【解决方案2】:

      我也不确定你想要什么,但这个功能可能会有所帮助:

      combn
      

      这是一个简单的例子:

      > combn(letters[1:4], 2)
           [,1] [,2] [,3] [,4] [,5] [,6]
      [1,] "a"  "a"  "a"  "b"  "b"  "c" 
      [2,] "b"  "c"  "d"  "c"  "d"  "d" 
      

      我认为这不是您想要的,但如果您澄清一下,也许我可以编辑以获得您想要的:

      > sham1<-c('a','b')
      > sham2<-c('d','e')
      > combn(c(sham1,sham2),2)
           [,1] [,2] [,3] [,4] [,5] [,6]
      [1,] "a"  "a"  "a"  "b"  "b"  "d" 
      [2,] "b"  "d"  "e"  "d"  "e"  "e" 
      

      【讨论】:

        【解决方案3】:

        combn 为您提供组合(因此,独一无二),但不是重复的组合。因此,将它与给你重复的东西结合起来,你就有了:

        c(combn(shams, 2, simplify=FALSE), 
          lapply(shams, function(s) list(s,s)))
        

        【讨论】:

          【解决方案4】:

          不知道你的例子在说什么。如果您想要独特的成对组合:

          strsplit(levels(interaction(sham1, sham2, sep="*")), "\\*")
          

          【讨论】:

          • 我编辑了我的问题以使其更清楚。我想要向量的成对组合,而不是元素
          【解决方案5】:

          我不明白你想要什么。而且您似乎更改了其他 question 的所需输出。
          你希望你的两个列表嵌套在另一个列表中的一个列表中??? 一次不是更简单吗?比如你有shams

          dput(shams)
          list(c("Sham1.r1", "Sham1.r2", "Sham1.r3"), c("Sham2.r1", "Sham2.r2", 
          "Sham2.r3"))
          

          要创建这样一个嵌套列表,您可以使用:

          combinations <- list(shams, "")
          dput(combinations)
          list(list(c("Sham1.r1", "Sham1.r2", "Sham1.r3"), c("Sham2.r1", "Sham2.r2", 
          "Sham2.r3"), "")
          

          虽然不是你说的那样……

          【讨论】:

            猜你喜欢
            • 2021-12-25
            • 2018-11-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-12-07
            • 2017-07-02
            相关资源
            最近更新 更多