Answer to: Calculate multilple stats for two or more columns in R data.table
Score: 1
An alternative where the function takes "all columns" (instead of individual columns).
stats2 <- function(frm) {
Map(function(x, nm) {
list(max(x), min(x)) |> setNames(paste0(nm, c("_maximo", "_minimo")))
}, frm, names(frm)) |>
unname() |>
do.call(cbind.data.frame, args = _)
}
dt[, stats2(.SD), by = class, .SDcols = c('val1', 'val2')]
# class val1_maximo val1_minimo val2_maximo val2_minimo
# <char> <int> <int> <num> <num>
# 1: a 9 1 120 30
# 2: b 11 2 90 10
# 3: c 12 4 110 50
Reproducible data:
set.seed(42)
dt <- data.table(class = rep(c('a', 'b', 'c'), 4),
val1 = sample(12),
val2 = sample(12)*10)
If .-separated names is okay instead of _, you can simplify stats2 a bit with
stats3 <- function(frm) {
lapply(frm, function(x) list(maximo = max(x), minimo = min(x))) |>
do.call(cbind.data.frame, args = _)
}
dt[, stats3(.SD), by = class, .SDcols = c('val1', 'val2')]
# class val1.maximo val1.minimo val2.maximo val2.minimo
# <char> <int> <int> <num> <num>
# 1: a 9 1 120 30
# 2: b 11 2 90 10
# 3: c 12 4 110 50
View Question ↗
Question
Parent Entity
Score: 2 • Views: 62
Site: stackoverflow
SaaS Metrics