按组的相关矩阵

时间:2014-05-31 06:21:07

标签: r plyr correlation hmisc

这是我的数据框

df <- structure(list(g1 = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L), .Label = c("A", "C"), class = "factor"), g2 = structure(c(1L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L), .Label = c("a", "b"), class = "factor"), v1 = 1:10, v2 = c(5, 5, 6, 2, 4, 4, 2, 1, 9, 8), v3 = c(29, 10, 56, 93, 20, 14, 12, 87, 67, 37)), .Names = c("g1", "g2",  "v1", "v2", "v3"), row.names = c(NA, -10L), class = "data.frame")

   g1 g2 v1 v2 v3
1   A  a  1  5 29
2   A  a  2  5 10
3   A  a  3  6 56
4   A  b  4  2 93
5   A  b  5  4 20
6   C  a  6  4 14
7   C  a  7  2 12
8   C  b  8  1 87
9   C  b  9  9 67
10  C  b 10  8 37

我想为组g1和g2(在这种情况下为Aa,Ab,Ca,Cb)的每个组合创建v1,v2和v3的相关矩阵。所以我想使用包Hmisc并与plyr结合

library(Hmisc)
library(plyr)

这有效(当然忽略了群体):

rcorr(as.matrix(df[,3:5]), type="pearson")

但这不是:

cor.matrix <- dlply(df, .(g1,g2), rcorr(as.matrix(df[,3:5]), type="pearson"))
Error:attempt to apply non-function

我做错了什么?

1 个答案:

答案 0 :(得分:1)

如果每组有超过4个观察值(这就是为什么rbinddf加上df另外2个df <- structure(list(g1 = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L), .Label = c("A", "C"), class = "factor"), g2 = structure(c(1L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 2L), .Label = c("a", "b"), class = "factor"), v1 = 1:10, v2 = c(5, 5, 6, 2, 4, 4, 2, 1, 9, 8), v3 = c(29, 10, 56, 93, 20, 14, 12, 87, 67, 37)), .Names = c("g1", "g2", "v1", "v2", "v3"), row.names = c(NA, -10L), class = "data.frame") df <- rbind(df, df, df) library(Hmisc) lapply(split(df, df[, 1:2]), function(x) { rcorr(as.matrix(x[,3:5]), type="pearson") }) 的原因,这是有效的:

dlply(df, .(g1,g2), function(x) rcorr(as.matrix(x[,3:5]), type="pearson"))

编辑这有效:

{{1}}