我想计算R中的相关性。但是我有很多缺失值。因此,我想在相关矩阵中承认仅从至少10对值计算的相关性。 怎么办?
编辑: 请注意,相关矩阵是由具有相同个体(行)的两个大矩阵X和Y生成的。
答案 0 :(得分: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