bvowe
bvowe

Reputation: 3384

R DataTable Convert Data To Mean and Quantiles

data = data.frame(a = runif(100), b = runif(100), c = runif(100), d = runif(100))

If I wish to convert to a mean of all a, b, c and d I can do this:

setDT(data)
dataMEAN <- data[, lapply(.SD, mean)]

But What if I am searching for the mean and quantiles such as

quantile(data$a, probs=c(.10,.90))

How can I do this all at once in data.table and fill in such a data.table like this:

enter image description here

Upvotes: 1

Views: 132

Answers (1)

akrun
akrun

Reputation: 887098

We can melt the data to 'long' format, grouped by 'variable', get the mean in a list, concatenate with the list column created with quantile

library(data.table)
out <- melt(setDT(data))[, c(list(MEAN = mean(value)), 
      as.list(quantile(value, probs = c(.10, .90)))), variable]
out
#   variable      MEAN        10%       90%
#1:        a 0.4903088 0.04842401 0.8790265
#2:        b 0.4890356 0.11788974 0.9221995
#3:        c 0.4890958 0.12364468 0.8670124
#4:        d 0.4638097 0.06690734 0.9448844

setnames(out, 3:4, c('LOWER', 'UPPER'))

Or use setNames within the melt

melt(setDT(data))[, c(list(MEAN = mean(value)), 
  setNames(as.list(quantile(value, probs = c(.10, .90))), 
       c('LOWER', 'UPPER'))), variable]

Upvotes: 2

Related Questions