[英]correlation between columns by group
如何在不使用列名的情况下计算 R 中数据框中的一列与所有其他列之间的相关性? 我尝试使用 ddply,如果我只使用两个列名,它就可以工作,即
library(plyr)
ddply(iris, ~Species, summarize, cormat=cor(Sepal.Length,Petal.Width))
但是如何在不使用列名的情况下获得第 1 列与所有其他列的相关性,按物种细分?
也许像这样? 它为每个物种生成一个相关矩阵。
by(iris[,1:4], iris$Species, cor)
您可以使用 dplyr 执行此操作
library(dplyr)
cormat_res <- iris %>%
group_by(Species) %>%
do(cormat = cor(select(., -matches("Species"))))
> cormat_res[[2]]
[[1]]
Sepal.Length Sepal.Width Petal.Length Petal.Width
Sepal.Length 1.0000000 0.7425467 0.2671758 0.2780984
Sepal.Width 0.7425467 1.0000000 0.1777000 0.2327520
Petal.Length 0.2671758 0.1777000 1.0000000 0.3316300
Petal.Width 0.2780984 0.2327520 0.3316300 1.0000000
[[2]]
Sepal.Length Sepal.Width Petal.Length Petal.Width
Sepal.Length 1.0000000 0.5259107 0.7540490 0.5464611
Sepal.Width 0.5259107 1.0000000 0.5605221 0.6639987
Petal.Length 0.7540490 0.5605221 1.0000000 0.7866681
Petal.Width 0.5464611 0.6639987 0.7866681 1.0000000
[[3]]
Sepal.Length Sepal.Width Petal.Length Petal.Width
Sepal.Length 1.0000000 0.4572278 0.8642247 0.2811077
Sepal.Width 0.4572278 1.0000000 0.4010446 0.5377280
Petal.Length 0.8642247 0.4010446 1.0000000 0.3221082
Petal.Width 0.2811077 0.5377280 0.3221082 1.0000000
截至
packageVersion("dplyr")
[1] ‘1.0.2’
答案之一中建议的代码结果返回一个tibble
iris %>%
group_by(Species) %>%
do(cormat = cor(select(., -matches("Species"))))
# A tibble: 3 x 2
# Rowwise:
Species cormat
<fct> <list>
1 setosa <dbl[,4] [4 × 4]>
2 versicolor <dbl[,4] [4 × 4]>
3 virginica <dbl[,4] [4 × 4]>
要将数据变成矩形,您可以
iris_cor <- iris %>%
group_by(Species) %>%
do(cormat = cor(select(., -matches("Species")))) %>%
pull(cormat) %>% melt
您将在L1
变量上编码物种的级别。
Var1 Var2 value L1
1 Sepal.Length Sepal.Length 1.0000000 1
2 Sepal.Width Sepal.Length 0.7425467 1
3 Petal.Length Sepal.Length 0.2671758 1
4 Petal.Width Sepal.Length 0.2780984 1
...
我确信使用unnest()
和它的朋友有一种更干净的方法,但还没有弄清楚。 希望这会引起注意并发布更好的解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.