cor()函数的Complete.obs

cor()函数的Complete.obs,r,matrix,correlation,na,R,Matrix,Correlation,Na,我正在为我的数据建立一个相关矩阵,如下所示 df <- structure(list(V1 = c(56, 123, 546, 26, 62, 6, NA, NA, NA, 15 ), V2 = c(21, 231, 5, 5, 32, NA, 1, 231, 5, 200), V3 = c(NA, NA, 24, 51, 53, 231, NA, 153, 6, 700), V4 = c(2, 10, NA, 20, 56, 1, 1, 53, 40, 5000)), .Names

我正在为我的数据建立一个相关矩阵,如下所示

df <- structure(list(V1 = c(56, 123, 546, 26, 62, 6, NA, NA, NA, 15
), V2 = c(21, 231, 5, 5, 32, NA, 1, 231, 5, 200), V3 = c(NA, 
NA, 24, 51, 53, 231, NA, 153, 6, 700), V4 = c(2, 10, NA, 20, 
56, 1, 1, 53, 40, 5000)), .Names = c("V1", "V2", "V3", "V4"), row.names = c(NA, 
10L), class = "data.frame")
我通常使用complete.obs命令来使用此命令建立相关矩阵

crm <- cor(df, use="complete.obs", method="pearson") 

crm查看
cor
的帮助文件,即
?cor
。特别是,

如果“use”是“everything”,那么“NA”将在概念上传播,即a 只要其中一个贡献值为“NA”,则结果值为“NA” 观察值为“NA”

如果“use”为“all.obs”,则表示缺少观测值 将产生一个错误。如果“use”为“complete.obs”,则缺少 通过按大小写删除(如果没有完整的 案例,这会给出一个错误)

要更好地了解正在发生的事情,请创建一个(甚至)更简单的示例:

df1 = df[1:5,1:3]
cor(df1, use="pairwise.complete.obs", method="pearson") 
cor(df1, use="complete.obs", method="pearson") 
cor(df1[3:5,], method="pearson") 

因此,当我们使用
complete.obs
时,如果存在
NA
,我们将丢弃整行。在我的示例中,这意味着我们放弃第1行和第2行。但是,
pairwise.complete.obs
在计算
V1
V2
之间的相关性时使用非
NA
值。谢谢您的回复,我已经阅读了帮助页面,我相信我正在寻找“pairwise.complete.obs”。我不确定这句话的意思是什么,“这会导致协方差或相关矩阵不是半正定的,如果这对变量没有完整的对,也会导致NA条目”。我的数据中确实有“无完整对”(例如V1和V2之间的第7行),但使用“pairwise.complete.obs”并没有显示NA。如果你能告诉我前一句话的意思,那将非常有帮助。干杯
df2 <- structure(list(V1 = c(26, 62, 15), V2 = c(5, 32, 200), V3 = c(51, 
53, 700), V4 = c(20, 56, 5000)), .Names = c("V1", "V2", "V3", 
"V4"), row.names = c(NA, 3L), class = "data.frame")
df1 = df[1:5,1:3]
cor(df1, use="pairwise.complete.obs", method="pearson") 
cor(df1, use="complete.obs", method="pearson") 
cor(df1[3:5,], method="pearson")