I am trying to apply multiple functions to multiple columns of a data.table
. Example:
DT <- data.table("a"=1:5, "b"=2:6, "c"=3:7)
Let's say I want to get the mean and the median of columns a
and b
. This works:
stats <- DT[,.(mean_a=mean(a), median_a=median(a), mean_b=mean(b), median_b=median(b))]
But it is way too repetitive. Is there a nice way to achieve a similar result using .SDcols
and lapply
?
I'd normally do this:
my.summary = function(x) list(mean = mean(x), median = median(x)) DT[, unlist(lapply(.SD, my.summary)), .SDcols = c('a', 'b')] #a.mean a.median b.mean b.median # 3 3 4 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With