【问题标题】:How to get only unique combinations of variables where entries can be in either variable如何仅获取变量的唯一组合,其中条目可以在任一变量中
【发布时间】:2014-05-30 00:23:10
【问题描述】:

鉴于我们有

j<-c("a","b","c","d")  
l<-expand.grid(j,j)

print(l)

Var1 Var2
1     a    a
2     b    a
3     c    a
4     d    a
5     a    b
6     b    b
7     c    b
8     d    b
9     a    c
10    b    c
11    c    c
12    d    c
13    a    d
14    b    d
15    c    d
16    d    d

我只想返回唯一的条目,例如:

print(newl)
Var1 Var2
a    a
a    b
a    c
a    d
b    b
b    c
b    d
c    c
c    d
d    d

我找到了很多答案,其中变量的独特组合,但变量不跨列。

这一切都来自于执行 corr.test {psych} 并使用 as.vector(corr.test$r) 将 corr.test$r 展开为单个向量。

为了获得这些基于我使用的相关性

names<-expand.grid(rownames(corr.test$r),colnames(corr.test$r))

最终与 as.vector 中“展开”的 r 矩阵的结构一致。

但它返回整个矩阵(上下三角形)。因此,我正在寻找一种仅采用唯一相关性(data.frame 的一半)的方法。

【问题讨论】:

标签: r


【解决方案1】:

combn 函数将为您提供向量中元素的所有n-组合,但它与元素本身不匹配。您可以相当轻松地添加该结果,因此您可以获得所需的组合

cbind(combn(j,2), rbind(j,j))

#   [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# j "a"  "a"  "a"  "b"  "b"  "c"  "a"  "b"  "c"  "d"  
# j "b"  "c"  "d"  "c"  "d"  "d"  "a"  "b"  "c"  "d"  

【讨论】:

    【解决方案2】:

    您可以重塑数据以避免这种情况

    library(psych)
    library(reshape2)
    
    # example data
    dat <- mtcars[1:4]
    
    # For all correlations
    melt(corr.test(dat)$r)
    
    # For unique correlations
    out <- corr.test(dat)$r
    out[upper.tri(out)] <- NA    
    
    melt(out, na.rm=TRUE)
    
       Var1 Var2      value
    #  1   mpg  mpg  1.0000000
    #  2   cyl  mpg -0.8521620
    #  3  disp  mpg -0.8475514
    #  4    hp  mpg -0.7761684
    #  6   cyl  cyl  1.0000000
    #  7  disp  cyl  0.9020329
    #  8    hp  cyl  0.8324475
    #  11 disp disp  1.0000000
    #  12   hp disp  0.7909486
    #  16   hp   hp  1.0000000
    

    【讨论】:

      【解决方案3】:

      您可以做的一件事是将答案放入一个数组中,使用 Var1 作为键,Var2 作为值,然后如果该对在临时数组中不存在,则将这些对添加到一个临时数组中。

      【讨论】:

        【解决方案4】:

        感谢您的回答。

        我最终拍了一张照片,这是我想出的:

        j<-c("a","b","c","d")  
        l<-expand.grid(j,j)
        
        
        twist<-function(l){
        l<-subset(l,l[,1]!=l[,2])
        leng<-length(l[,1])/2
        for (i in 1:leng) {
            g1<-l[,1]
            g2<-l[,2]
            g1[i]<-l[i,2]
            g2[i]<-l[i,1]
            l[,1]<-g1
            l[,2]<-g2
        l<-unique(l[c("Var1", "Var2")])
        
        }
        return(l)
        }
        k<-twist(l)
        
        print(k)
        
           Var1 Var2
        2     a    b
        3     a    c
        4     a    d
        7     b    c
        8     b    d
        12    c    d
        

        出于非常明显的原因,我将其称为“扭曲”。欢迎批评。

        【讨论】:

        • 快速说明,您可以使用 t(combn(j,2)) 完成此操作
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-24
        • 2016-07-08
        • 2023-02-01
        • 2012-05-02
        相关资源
        最近更新 更多