Вот еще один способ сделать это:
# split the data by group then apply spearman correlation
# to each element of that list
j <- lapply(split(df, df$group), function(x){cor(x[,2], x[,3], method = "spearman")})
# Bring it together
data.frame(group = names(j), corr = unlist(j), row.names = NULL)
Сравнение моего метода, метода Джоша и решения plyr с использованием rbenchmark:
Dason <- function(){
# split the data by group then apply spearman correlation
# to each element of that list
j <- lapply(split(df, df$group), function(x){cor(x[,2], x[,3], method = "spearman")})
# Bring it together
data.frame(group = names(j), corr = unlist(j), row.names = NULL)
}
Josh <- function(){
r <- by(df, df$group, FUN = function(X) cor(X$var1, X$var2, method = "spearman"))
data.frame(group = attributes(r)$dimnames[[1]], corr = as.vector(r))
}
plyr <- function(){
ddply(df, .(group), summarise, "corr" = cor(var1, var2, method = "spearman"))
}
library(rbenchmark)
benchmark(Dason(), Josh(), plyr())
, который дает вывод
> benchmark(Dason(), Josh(), plyr())
test replications elapsed relative user.self sys.self user.child sys.child
1 Dason() 100 0.19 1.000000 0.19 0 NA NA
2 Josh() 100 0.24 1.263158 0.22 0 NA NA
3 plyr() 100 0.51 2.684211 0.52 0 NA NA
Так что, похоже, мой метод немного быстрее, но ненамного.Я думаю, что метод Джоша немного более интуитивно понятен.Решение plyr проще всего кодировать, но оно не самое быстрое (но оно гораздо удобнее)!