在R中,一个变量与其他所有变量的相关性

15

我想计算我的因变量y和所有自变量x之间的相关性。我使用下面的代码:

   cor(loan_data_10v[sapply(loan_data_10v, is.numeric)],use="complete.obs")

结果是一个相关矩阵。我该如何仅获取包含我的变量y的一列。


2
cor(load_data_10v)[,1]? - r2evans
是的,这个也可以。谢谢!!! - Pumpkin C
由于我的y是10,我使用了[,10],它有效。但如果我不知道我的y是第10个,而是最后一个,我尝试了[,-1],但这给了我所有的东西。为什么会这样呢?我以为它会切片最后一列。 - Pumpkin C
抱歉,我不知道你在说什么。[,-1] 给出除了第一列之外的所有列,这就是负数的意图所在(请参考 https://stat.ethz.ch/R-manual/R-devel/library/base/html/Extract.html)。 - r2evans
好的,明白了,谢谢! - Pumpkin C
显示剩余2条评论
2个回答

23
如果我们正在寻找“x”和“y”之间的“cor”,则两个参数可以是矢量或矩阵。使用可重复的示例,例如mtcars,假设“y”是“mpg”,而“x”是其他变量(因为“mpg”是第一列,所以我们对“x”使用了mtcars[-1])。
cor(mtcars[-1], mtcars$mpg) 
#          [,1]
#cyl  -0.8521620
#disp -0.8475514
#hp   -0.7761684
#drat  0.6811719
#wt   -0.8676594
#qsec  0.4186840
#vs    0.6640389
#am    0.5998324
#gear  0.4802848
#carb -0.5509251
如果我们有数字/非数字列,创建一个数字列的索引('i1'),使用此索引获取'x'和'y'变量的名称并应用cor
i1 <- sapply(loan_data_10v, is.numeric)
y1 <- "dep_column" #change it to actual column name
x1 <- setdiff(names(loan_data_10v)[i1], y1)
cor(loan_data_10v[x1], loan_data_10v[[y1]])

1
谢谢!它起作用了。我在cor中添加了use="complete.obs",因为我的每个变量都有na值。 - Pumpkin C
嘿,akrun,有没有用data.table实现这个解决方案的方式?我在这里发布了一个问题:https://stackoverflow.com/questions/56182271/getting-the-correlation-with-significance-of-one-variable-with-the-rest-of-the-d. - Tom

1
另一个选择是使用corrr包,您可以轻松指定要关注的变量,并返回一个data.frame
library(tidyverse)
library(corrr)
mtcars %>% 
  correlate() %>% 
  focus(mpg) 
# Correlation computed with
# • Method: 'pearson'
# • Missing treated using: 'pairwise.complete.obs'
# # A tibble: 10 × 2
#    term     mpg
#    <chr>  <dbl>
#  1 cyl   -0.852
#  2 disp  -0.848
#  3 hp    -0.776
#  4 drat   0.681
#  5 wt    -0.868
#  6 qsec   0.419
#  7 vs     0.664
#  8 am     0.600
#  9 gear   0.480
# 10 carb  -0.551

如果你想先移除其他非数字变量,这个也很有用,例如:
iris %>% 
  select_if(~!is.factor(.)) %>% 
  correlate() %>% 
  focus(Petal.Width)
# Correlation computed with
# • Method: 'pearson'
# • Missing treated using: 'pairwise.complete.obs'
# # A tibble: 3 × 2
#   term         Petal.Width
#   <chr>              <dbl>
# 1 Sepal.Length       0.818
# 2 Sepal.Width       -0.366
# 3 Petal.Length       0.963

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接