I am trying to calculate grouped means using collapse package. Below is an example of what I am trying to achieve.
library(data.table)
library(collapse)
data_1 <- as.data.table(airquality)
var_means <- c(
"Ozone",
"Solar.R",
"Wind"
)
data_1[,paste0(var_means,"_mean") := lapply(.SD,mean,na.rm = TRUE),by = .(Month)]
CodePudding user response:
There are at least a couple of ways. Using the dplyr
-style syntax:
library(collapse)
var_means <- c(
"Ozone",
"Solar.R",
"Wind"
)
airquality |>
fgroup_by(Month) |>
fmutate(across(var_means, fmean, .names = TRUE)) |>
fungroup()
Or using ftransform()
:
ftransform(airquality,
fmean(
list(
Ozone_mean = Ozone,
Solar.R_mean = Solar.R,
Wind_mean = Wind
),
g = Month,
TRA = 1
))
Or if you want to pass a character vector of columns you need something like:
ftransform(airquality,
fmean(
do.call(list, lapply(setNames(var_means, paste0(var_means, "_mean")), as.name)),
g = Month,
TRA = 1
))