【问题标题】:correlation computation with threshold in RR中的阈值相关计算
【发布时间】:2011-10-03 09:34:36
【问题描述】:

我想计算 R 中的相关性。但是我有很多缺失值。因此,我想在相关矩阵中承认仅从至少 10 对值计算的相关性。 如何进行?

编辑: 请注意,相关矩阵是由具有相同个体(行)的两个大矩阵 X 和 Y 生成的。

【问题讨论】:

  • 我不明白您的编辑。您可以使用as.data.frame 轻松地将 data.frame 转换为矩阵,反之亦然

标签: r correlation


【解决方案1】:

首先我们生成一些示例数据:

R> x = matrix(rnorm(100), ncol=5)
##Fill in some NA's
R> x[3:15,1] = NA
R> x[2:10,3] = NA

接下来我们循环遍历x 矩阵进行比较以检测 NA:

##Create a matrix with where the elements are the
##maximum number of possible comparisons 
m = matrix(nrow(x), ncol=ncol(x),nrow=ncol(x)) 
## This comparison can be made more efficient. 
## We only need to do column i with i+1:ncol(x)

## Each list element
for(i in 1:ncol(x)) {
    detect_na = is.na(x[,i]==x)
    c_sums = colSums(detect_na)
    m[i,] = m[i,] - c_sums
}

矩阵m 现在包含每列对的比较次数。现在转换m 矩阵以准备子集:

 m = ifelse(m>10, TRUE, NA)

接下来我们根据m计算所有列对和子集的相关性:

R> matrix(cor(x, use = "complete.obs")[ m], ncol=ncol(m), nrow=nrow(m))
     [,1]    [,2]     [,3]    [,4]    [,5]
[1,]   NA      NA       NA      NA      NA
[2,]   NA  1.0000 -0.14302 0.35902 -0.3466
[3,]   NA -0.1430  1.00000 0.03949  0.6172
[4,]   NA  0.3590  0.03949 1.00000  0.1606
[5,]   NA -0.3466  0.61720 0.16061  1.0000

【讨论】:

  • 但是您的解决方案对于大矩阵需要太多时间
  • 我认为大矩阵不会有问题,因为您的标准是至少有 10 个观察值。如果您有很多列,您可以在循环之前删除少于十个观察值的列。
猜你喜欢
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 2021-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多