Answer to: Calculate multilple stats for two or more columns in R data.table
Score: 1
You need to modify stats to accept an array (one column per numeric variable) and return a simple list (not a list of lists). Keeping everything as lists (instead of arrays or matrices) within stats will preserve the names needed to identify the columns.
stats <- function(x) {
stat <- function(x) {
y <- quantile(x, c(1/4, 1/2, 3/4))
names(y) <- c("Q1", "M", "Q3")
as.list(y)
}
if (!is.matrix(x)) x <- matrix(x, ncol = 1)
as.list(unlist(apply(x, 2, stat)))
}
When using more than one value column, create the array argument to stats with cbind:
dt[, c(stats(cbind(val1, val2))), keyby = .(class)]
class val1.Q1 val1.M val1.Q3 val2.Q1 val2.M val2.Q3
<char> <num> <num> <num> <num> <num> <num>
1: a 8.0 9.5 10.25 67.5 95 112.5
2: b 2.5 3.5 4.75 55.0 65 77.5
3: c 5.0 7.0 9.00 17.5 35 60.0
View Question ↗
Question
Parent Entity
Score: 2 • Views: 62
Site: stackoverflow
SaaS Metrics