R中的cor()行为在各个向量和data.frame之间有所不同

haw*_*ler 5 r pearson correlation dataframe

我试图获得数据框中所有行相对于彼此的Pearson相关系数.有些值是空的(NA),这似乎是一个问题,我在两个缺少值的向量上运行cor()时没有遇到这个问题.这是2个向量的正确结果:

x <- c(NA, 4.5, NA, 4, NA, 1)
y <- c(2.5, 3.5, 3, 3.5, 3, 2.5)
cor(x,y, use = "complete.obs")
[1] 0.9912407
Run Code Online (Sandbox Code Playgroud)

这是结果,当它们是数据框的一部分时:

cor(t(critics1), use = "complete.obs")
   y  a  b  c  d  e  x
y  1 NA NA NA NA NA NA
a NA  1  1  1 -1  1 -1
b NA  1  1  1 -1  1 -1
c NA  1  1  1 -1  1 -1
d NA -1 -1 -1  1 -1  1
e NA  1  1  1 -1  1 -1
x NA -1 -1 -1  1 -1  1
Warning message:
In cor(t(critics1), use = "complete.obs") : the standard deviation is zero
Run Code Online (Sandbox Code Playgroud)

为什么使用参数不具有相同的效果?这是批评者1数据帧的样子;

film1 film2 film3 film4 film5 film6
y   2.5   3.5   3.0   3.5   3.0   2.5
a   3.0   3.5   1.5   5.0   3.0   3.5
b   2.5   3.0    NA   3.5   4.0    NA
c    NA   3.5   3.0   4.0   4.5   2.5
d   3.0   4.0   2.0   3.0   3.0   2.0
e   3.0   4.0    NA   5.0   3.0   3.5
x    NA   4.5    NA   4.0    NA   1.0
Run Code Online (Sandbox Code Playgroud)

Jos*_*ien 7

正如@joran推测的那样,当你进行转置时critics1,只有两个完整的观察结果(即没有缺失值的行).这就是为什么所有的相关的或者是1-1或(对于那些涉及y,其中有两个完整的行值3.5), NA.

t(critics1)
#         y   a   b   c d   e   x
# film1 2.5 3.0 2.5  NA 3 3.0  NA
# film2 3.5 3.5 3.0 3.5 4 4.0 4.5
# film3 3.0 1.5  NA 3.0 2  NA  NA
# film4 3.5 5.0 3.5 4.0 3 5.0 4.0
# film5 3.0 3.0 4.0 4.5 3 3.0  NA
# film6 2.5 3.5  NA 2.5 2 3.5 1.0
Run Code Online (Sandbox Code Playgroud)

如果您使用use="pairwise.complete.obs"而不是use="complete.obs",它可以按照您的意愿使用:

cor(t(df), use="pairwise.complete.obs")["y","x"] # Extract correlation of y and x
# [1] 0.9912407
Run Code Online (Sandbox Code Playgroud)