我正在为我的数据建立一个相关矩阵,它看起来像这样
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")
这给出了以下数据框:
V1 V2 V3 V4
1 56 21 NA 2
2 123 231 NA 10
3 546 5 24 NA
4 26 5 51 20
5 62 32 53 56
6 6 NA 231 1
7 NA 1 NA 1
8 NA 231 153 53
9 NA 5 6 40
10 15 200 700 5000
我通常使用 complete.obs 命令来使用此命令建立我的相关矩阵
crm <- cor(df, use="complete.obs", method="pearson")
我的问题是,complete.obs 如何处理数据?它是否省略了任何具有“NA”值的行,创建一个“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")
或者它是否以成对的方式省略“NA”值,例如在计算 V1 和 V2 之间的相关性时,V3 中包含 NA 值的行(例如我的示例中的第 1 行和第 2 行)它们是否也被省略了?
如果是这种情况,我期待通过以成对方式省略 NA 值来建立一个保留尽可能多数据的命令。
非常感谢,
最佳答案
查看 cor
的帮助文件,即 ?cor
.特别是,
If ‘use’ is ‘"everything"’, ‘NA’s will propagate conceptually, i.e., a resulting value will be ‘NA’ whenever one of its contributing observations is ‘NA’.
If ‘use’ is ‘"all.obs"’, then the presence of missing observations will produce an error. If ‘use’ is ‘"complete.obs"’ then missing values are handled by casewise deletion (and if there are no complete cases, that gives an error).
为了更好地了解正在发生的事情,是创建一个(甚至)更简单的示例:
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
使用非 NA
计算 V1
之间的相关性时的值和 V2
.
关于r - cor() 函数的完整.obs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18892051/