我想计算我的因变量y和所有自变量x之间的相关性。我使用下面的代码:
cor(loan_data_10v[sapply(loan_data_10v, is.numeric)],use="complete.obs")
结果是一个相关矩阵。我该如何仅获取包含我的变量y的一列。
我想计算我的因变量y和所有自变量x之间的相关性。我使用下面的代码:
cor(loan_data_10v[sapply(loan_data_10v, is.numeric)],use="complete.obs")
结果是一个相关矩阵。我该如何仅获取包含我的变量y的一列。
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]])
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
cor(load_data_10v)[,1]
? - r2evans[,-1]
给出除了第一列之外的所有列,这就是负数的意图所在(请参考 https://stat.ethz.ch/R-manual/R-devel/library/base/html/Extract.html)。 - r2evans