5

我正在尝试获取数据框中所有行相对于彼此的 Pearson 相关系数。有些值是空的(NA),这似乎是我在 2 个缺少值的向量上运行 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

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

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

为什么使用参数没有相同的效果?这是crictors1 数据框的样子;

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
4

1 回答 1

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

如果您使用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
于 2011-12-06T19:19:48.650 回答