我想在data.table中调用一个函数来计算一组汇总统计信息,如下所示:
summ.stats <- function(vec) {
list(
Min = min(vec),
Mean = mean(vec),
S.D. = sd(vec),
Median = median(vec),
Max = max(vec))
}
我希望在j
的{{1}}中调用它:
data.table
这很好,我明白了:
DT <- data.table(a=c(1,2,3,1,2,3),b=c(1,4,3,2,1,4),c=c(2,3,4,5,2,1))
DT[, summ.stats(b), by=a]
但我有兴趣将多个变量传递给summ.stats。例如:
a Min Mean S.D. Median Max
1: 1 1 1.5 0.7071068 1.5 2
2: 2 1 2.5 2.1213203 2.5 4
3: 3 3 3.5 0.7071068 3.5 4
我希望得到类似的内容:
DT[, summ.stats(b, c), by=a]
最好的方法是什么?
答案 0 :(得分:5)
或者您可以按如下方式修改您的功能:
summ.stats <- function(vec) {
list(
Var = names(vec),
Min = sapply(vec, min),
Mean = sapply(vec, mean),
S.D. = sapply(vec, sd),
Median = sapply(vec, median),
Max = sapply(vec, max))
}
DT[, summ.stats(.SD), by=a] # no need for as.list(.SD) as Roger mentions
a Var Min Mean S.D. Median Max
1: 1 b 1 1.5 0.7071068 1.5 2
2: 1 c 2 3.5 2.1213203 3.5 5
3: 2 b 1 2.5 2.1213203 2.5 4
4: 2 c 2 2.5 0.7071068 2.5 3
5: 3 b 3 3.5 0.7071068 3.5 4
6: 3 c 1 2.5 2.1213203 2.5 4
答案 1 :(得分:3)
如果没有明确地重塑为长形式,您可以执行类似
的操作rbindlist(lapply(c('b','c'), function(x) data.table(var = x, DT[,summ.stats(get(x)),by=a])))
# var a Min Mean S.D. Median Max
# 1: b 1 1 1.5 0.7071068 1.5 2
# 2: b 2 1 2.5 2.1213203 2.5 4
# 3: b 3 3 3.5 0.7071068 3.5 4
# 4: c 1 2 3.5 2.1213203 3.5 5
# 5: c 2 2 2.5 0.7071068 2.5 3
# 6: c 3 1 2.5 2.1213203 2.5 4
如果reshape
数据为长篇
reshape(DT, direction = 'long',
varying = list(value = c('b','c')),
times = c('b','c'))[,summ.stats(b), by = list(a, Var = time)]
也可以。
效率较低,你可以使用plyr的ldply
,稍微重新定义一下这个函数
summ.stats2 <- function(vec) {
data.table(
Min = min(vec),
Mean = mean(vec),
S.D. = sd(vec),
Median = median(vec),
Max = max(vec))
}
library(plyr)
DT[, ldply(lapply(.SD, summ.stats2)),by =a]