【问题标题】:How to create a pairwise matrix with counts of matching entries for comparisons of all levels of one factor in a dataframe?如何创建具有匹配条目计数的成对矩阵,以比较数据框中一个因素的所有级别?
【发布时间】:2017-05-25 00:05:35
【问题描述】:

我有一个包含两个变量的两列数据框:

df

PLOT  INTERACTION 
 A    interact_type_1
 A    interact_type_2
 B    interact_type_3
 B    interact_type_4 
 C    interact_type_1
 D    interact_type_4
 E    interact_type_1
 E    interact_type_2
 E    interact_type_3
 E    interact_type_4

我需要一个成对矩阵,其中 nrows 和 mcolumns 是变量 1 (PLOTS) 的唯一级别。矩阵填充将包括每个 PLOT 级别组合之间的 INTERACTION 匹配计数。因为它是一个相似矩阵,所以只有 1/2 的矩阵填充,所以相同的 PLOTS 和 1/2 的矩阵将被 NA 填充。在本例中,输出矩阵如下所示:

output


   A   B    C    D    E

A NA   NA   NA   NA   NA

B 0   NA    NA   NA   NA

C 1   0    NA    NA   NA

D 0   1    0    NA    NA

E 2   2    1    1     NA

我尝试将它从长格式更改为宽格式,然后使用循环:

 df<- spread(df, df$PLOT, df$INTERACTION) 


 similarity.matrix<-matrix(nrow=ncol(F.data),ncol=ncol(F.data))


 for( in 1:ncol(F.data)){
  matches<-F.data[,col]==F.data
  match.counts<-colSums(matches)
  match.counts[col]<-0 # Set the same column comparison to zero.
  similarity.matrix[,col]<-match.counts
   }  

但我收到第一行错误,指出错误:无效的列规范。

感谢您的宝贵时间和帮助!谢谢你。

【问题讨论】:

标签: r


【解决方案1】:

你可以这样做:

x = xtabs(~PLOT+INTERACTION,d)
        INTERACTION
    PLOT interact_type_1 interact_type_2 interact_type_3 interact_type_4
       A               1               1               0               0
       B               0               0               1               1
       C               1               0               0               0
       D               0               0               0               1
       E               1               1               1               1

使用combn 找出PLOT 中两个的组合:

n = length(unique(d$PLOT))
c = combn(1:n,2)

然后构造你的矩阵并填充它的下半部分:

m = matrix(nrow=n,ncol=n)
## for each possible combination of two present in c, we find for the corresponding rows in x how many 1s they have in common using sum(x[y[1],]*x[y[2],])
m[lower.tri(m)] = apply(c,2,function(y) sum(x[y[1],]*x[y[2],]))

这会返回:

      [,1] [,2] [,3] [,4] [,5]
[1,]   NA   NA   NA   NA   NA
[2,]    0   NA   NA   NA   NA
[3,]    1    0   NA   NA   NA
[4,]    0    1    0   NA   NA
[5,]    2    2    1    1   NA

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 2013-11-24
    相关资源
    最近更新 更多