5

我想在 data.table 中调用一个函数,该函数计算一组汇总统计信息,如下所示:

summ.stats <- function(vec) {
    list(
         Min = min(vec),
         Mean = mean(vec),
         S.D. = sd(vec),
         Median = median(vec),
         Max = max(vec))
}

我想在ja中调用它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]

这很好,我得到:

   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

但我有兴趣将多个变量传递给 summ.stats。例如:

DT[, summ.stats(b, c), by=a]

我想得到类似的东西:

   a Var Min Mean      S.D. Median Max
1: 1   b   1  1.5 0.7071068    1.5   2
2: 2   b   1  2.5 2.1213203    2.5   4
3: 3   b   3  3.5 0.7071068    3.5   4
4: 1   c   2  3.5 2.1213203    3.5   5
5: 2   c   2  2.5 0.7071068    2.5   3
6: 3   c   1  2.5 2.1213203    2.5   4

做这个的最好方式是什么?

4

2 回答 2

6

或者,您可以按如下方式修改您的功能:

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
于 2013-07-28T23:50:38.710 回答
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)]

也会起作用。


您可以ldply从 plyr 使用效率较低,只需稍微重新定义函数

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]
于 2013-07-28T22:52:53.997 回答