How to call a function that returns multiple rows and columns in a data.table?

前端 未结 2 429
醉酒成梦
醉酒成梦 2021-01-06 08:41

I want to call a function inside a data.table that calculates a set of summary statistics like the following:

summ.stats <- function(vec) {
    list(
             


        
2条回答
  •  伪装坚强ぢ
    2021-01-06 08:58

    Alternatively you can modify your function as follows:

    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
    

提交回复
热议问题