R中一个变量与所有其他变量的相关性 [英] correlation of one variable to all the other in R
问题描述
我想计算我的因变量y与所有我的x之间的相关性.我使用下面的代码,
I want to calculate the correlation between my dependent variable y and all my x. I use the code below,
cor(loan_data_10v[sapply(loan_data_10v, is.numeric)],use="complete.obs")
结果是一个相关矩阵.我如何只用变量y获得一列.
the result is a correlation matrix. How can i just get one column with my variable y.
推荐答案
如果我们要在'x'和'y'之间寻找 cor
,则两个参数都可以是 vector
或 matrix
.使用一个可重现的示例,假设 mtcars
并假设'y'是'mpg','x'是其他变量('mpg'是第一列,因此我们使用了 mtcars [-1]
表示"x")
If we are looking for cor
between 'x' and 'y', both argument can be either a vector
or matrix
. using a reproducible example, say mtcars
and suppose 'y' is 'mpg' and 'x' the other variables ('mpg' is the first column, so we used mtcars[-1]
for 'x')
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
如果我们有 numeric/non-numeric
列,则创建一个 numeric
列('i1')的索引,获得 names
的使用此索引的'x'和'y'变量并应用 cor
If we have numeric/non-numeric
columns, create an index of numeric
columns ('i1'), get the names
of 'x' and 'y' variables using this index and apply the 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]])
这篇关于R中一个变量与所有其他变量的相关性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!