0 r plyr correlation
我有一个data.frame,我想用一列相对于其他列(框架中也有一些非数字列)来计算相关系数。
ddply(Banks,.(brand_id,standard.quarter),function(x) { cor(BLY11,x) })
# Error in cor(BLY11, x) : 'y' must be numeric
Run Code Online (Sandbox Code Playgroud)
我针对is.numeric(x)进行了测试
ddply(Banks,.(brand_id,standard.quarter),function(x) { if is.numeric(x) cor(BLY11,x) else 0 })
Run Code Online (Sandbox Code Playgroud)
但是每次比较都失败,返回0,仅返回一列,就好像它仅被调用过一次一样。什么传递给该函数?刚来到R,我认为我缺少一些基本知识。
谢谢
从?cor:
如果“ x”和“ y”是矩阵,则计算“ x”的列与“ y”的列之间的协方差(或相关性)。
因此,您唯一真正的工作是删除非数字列:
# An example data.frame containing a non-numeric column
d <- cbind(fac=c("A","B"), mtcars)
## Calculate correlations between the mpg column and all numeric columns
cor(d$mpg, as.matrix(d[sapply(d, is.numeric)]))
mpg cyl disp hp drat wt qsec
[1,] 1 -0.852162 -0.8475514 -0.7761684 0.6811719 -0.8676594 0.418684
vs am gear carb
[1,] 0.6640389 0.5998324 0.4802848 -0.5509251
Run Code Online (Sandbox Code Playgroud)
编辑:实际上,正如@ MYaseen208的答案所示,无需将data.frames显式转换为矩阵。以下两个工作都很好:
cor(d$mpg, d[sapply(d, is.numeric)])
cor(mtcars, mtcars)
Run Code Online (Sandbox Code Playgroud)
尝试这样的事情
cor(longley[, 1], longley[ , sapply(longley, is.numeric)])
GNP.deflator GNP Unemployed Armed.Forces Population Year Employed
[1,] 1 0.9915892 0.6206334 0.4647442 0.9791634 0.9911492 0.9708985
Run Code Online (Sandbox Code Playgroud)