如何使用R创建同现矩阵

时间:2019-11-26 04:36:58

标签: r matrix

我正在尝试在数据中建立一个共现矩阵。我有141行和544列的数据框。每列包含0和1。数据集示例:

    OTU_1 OTU_10 OTU_100 OTU_101 OTU_109
    1      1       1       0        0
    1      1       0       0        1
    1      1       0       0        0
    1      1       1       1        1
    1      1       1       1        1

我的数据的原始结构:

data.frame':    141 obs. of  544 variables:
$ OTU_1    : Factor w/ 1 level "1": 1 1 1 1 1 1 1 1 1 1 ...
$ OTU_10   : Factor w/ 2 levels "0","1": 2 2 2 2 2 2 2 2 2 2 ...
$ OTU_100  : Factor w/ 2 levels "0","1": 2 1 1 2 2 2 1 2 2 2 ...

现在,我想一次将一列与其他列和另一行进行比较。因此,我尝试了以下代码:

gen.cyscd_df <- function(x){
help.df <- data.frame(otu1 = row.names(x)[1] , otu2 = rownames(x), counts= 0)
for (i in 1:ncol(x)){
help.df <- rbind.data.frame(help.df, data.frame(otu1 = col.names(x)[i] , 
                                                otu2 = col.names(x)[i:length(colnames(x))], 
                                                counts= 0))
}
row.names(help.df) <- NULL 
return(help.df) 
}
single.otu.df <- gen.cyscd_df(bin_OTU_tab)

以上代码的str为:

data.frame':    91961 obs. of  3 variables:
$ otu1  : Factor w/ 141 levels "1","2","3","4",..: 1 1 1 1 1 1 1 1 1 1 ...
$ otu2  : Factor w/ 141 levels "1","10","100",..: 1 54 65 76 87 98 109 120 131 2 ...
$ counts: num  0 0 0 0 0 0 0 0 0 0 ...

下一步是根据1个OTU与其他OTU的共存替换列数

single.otu.matrix_row <- function(x){
single.otu.df2 <- single.otu.df
for (otu1 in 1:nrow(x)){
for(otu2 in 1:nrow(x)){
  if(x[otu1,1] ==1 && x[otu2,1] ==1) {
    single.otu.df[otu1+otu2] <- 1}
}
}
return(single.otu.df2)
}
x<-single.otu.matrix_row(as.matrix(bin_OTU_tab[1:nrow(bin_OTU_tab),1]))

但是在counts列中,我无法替换0值。

data.frame':    91961 obs. of  3 variables:
     $ otu1  : Factor w/ 141 levels "1","2","3","4",..: 1 1 1 1 1 1 1 1 1 1 ...
     $ otu2  : Factor w/ 141 levels "1","10","100",..: 1 54 65 76 87 98 109 120 131 2 ...
     $ counts: num  0 0 0 0 0 0 0 0 0 0 ...

但是预期的输出是(对于第一行)

OTU1 OTU2 Counts
1     10    1
1     100   1
1     101   0
1     109   0

我哪里出错了。请指导我

0 个答案:

没有答案