2011-10-03 55 views
4

我想计算R中的相关性。但是我有很多缺失值。所以,我想在相关矩阵中只承认从至少10对值中计算出的相关性。 如何继续?R中的相关性计算与阈值

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

+0

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

回答

1

首先,我们产生了一些示例性数据:通过x矩阵

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

接下来我们循环做comparsion检测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 
+0

感谢您的回答 – Delphine

+0

然而,您的解决方案需要太多的时间来处理大型矩阵 – Delphine

+0

我不认为你会有一个由于您的标准具有至少** 10 **的观察结果,因此可能会出现大矩阵问题。如果您有很多列,则可以在循环前删除少于十个观察值的列。 – csgillespie