【问题标题】:R: Compare values in a read table and update another matrixR:比较读取表中的值并更新另一个矩阵
【发布时间】:2016-09-20 12:31:52
【问题描述】:

我目前在使用 R 比较特定矩阵中的每一列时遇到问题。我试图一次比较整个列中的每一列,并通过 table 命令生成真假输出,然后将可以找到的真数转换为数值并在它们各自的位置输入这些值关联矩阵。

For example, I have data in this type of format:
//Example state matrix - I am attempting to compare c1 with c2, then c1 with c3, then c1 with c4 and so on and so forth 
    c1  c2  c3  c4
r1  2   6   3   2
r2  1   1   6   5
r3  3   1   3   6

And I am trying to instead put it into this format
//Example incidence matrix - Which is how many times c1 equaled c2 in the above matrix 
    c1  c2  c3  c4
c1  3   1   1   1
c2  1   3   0   0
c3  1   0   3   0
c4  1   0   0   3

这里是我到目前为止想出的代码,但是,我不断收到这个特殊错误 --

警告信息: In IncidenceMat[rat][r] = IncidenceMat[rat][r] + as.numeric(instances) :要替换的项目数不是替换长度的倍数
rawData = read.table("5-14-2014streamW636PPstate.txt")
colnames = names(rawData) #the column names in R 
df <- data.frame(rawData)
rats = ncol(rawData) 
instances = nrow(rawData)

IncidenceMat = matrix(rep(0, rats), nrow = rats, ncol = rats) 

for(rat in rats)
   for(r in rats)
      if(rat == r){rawData[instance][rat] == rawData[instance][r] something like this would work in C++ if I attempted, 
        IncidenceMat[rat][r] = IncidenceMat[rat][r] + as.numeric(instances)
  } else{ 
    count = df[colnames[rat]] == df[colnames[r]]
    c = table(count)
    TotTrue = as.numeric(c[2][1])
    IncidenceMat[rat][r] = IncidenceMat[rat][r] + TotTrue #count would go here #this should work like a charm as well 
  }

任何帮助将不胜感激;我也查看了其中一些资源,但是我仍然感到困惑

I tried thisand this 以及我最近关闭的一些其他资源。

【问题讨论】:

    标签: r matrix analysis


    【解决方案1】:

    这个怎么样(注意关联矩阵是对称的)?

    df
       c1 c2 c3 c4
    r1  2  6  3  2
    r2  1  1  6  5
    r3  3  1  3  6
    
    incidence <- matrix(rep(0, ncol(df)*ncol(df)), nrow=ncol(df))
    diag(incidence) <- nrow(df)
    for (i in 1:(ncol(df)-1)) {
       for (j in (i+1):ncol(df)) {
         incidence[i,j] = incidence[j,i] = sum(df[,i] == df[,j])
       }
    }
    
    incidence
         [,1] [,2] [,3] [,4]
    [1,]    3    1    1    1
    [2,]    1    3    0    0
    [3,]    1    0    3    0
    [4,]    1    0    0    3
    

    【讨论】:

    • 这很好用!!! @sandipan 你介意解释一下你的思考过程吗?
    • 确定@zackymo21。首先注意关联矩阵的维度是 n x n,其中 n = 原始矩阵的 # 列(因为我们需要每 2 列进行比较)。还要注意,关联矩阵是对称的。所有对角线元素都将等于 n(因为每列恰好有 n 个元素与其自身相似)。最后我们需要计算列向量 i 和 j 之间的相似度,这可以用 sum(df[,i]==df[,j]) 来完成。
    • 我现在明白了!非常感谢您的澄清!我还有一个问题,你介意支持我的问题吗? @sandipan
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 2016-09-04
    • 1970-01-01
    • 2014-12-02
    相关资源
    最近更新 更多