I want to calculate the mean and standard deviation for subgroups every column in my dataset.
The membership of the subgroups is based on the values in the column of interest and these subgroups are specific to each column of interest.

```
# Example data
set.seed(1)
library(data.table)
df <- data.frame(baseline = runif(100), `Week0_12` = runif(100), `Week12_24` = runif(100))

```

So for column `Baseline`, a row may be assigned to another subgroup than for column `Week0_12`.

I can of course create these 'subgroup columns' manually for each column and then calculate the statistics for each column by column subgroup:

```
df$baseline_subgroup <- ifelse(df$baseline < 0.2, "subgroup_1", "subgroup_2")
df <- as.data.table(df)
df[, .(mean = mean(baseline), sd = sd(baseline)), by = baseline_subgroup]

```

Giving this output:

```
   baseline_subgroup       mean         sd
1:        subgroup_2 0.58059314 0.22670071
2:        subgroup_1 0.09793105 0.05317809

```

Doing this for every column separately is too much repetition, especially given that I have many columns my actual data.

```
df$Week0_12_subgroup <- ifelse(df$Week0-12 < 0.2, "subgroup_1", "subgroup_2")
df[, .(mean = mean(Week0_12), sd = sd(Week0_12 )), by = Week0_12_subgroup ]

df$Week12_24_subgroup <- ifelse(df$Week0-12 < 0.2, "subgroup_1", "subgroup_2")
df[, .(mean = mean(Week12_24), sd = sd(Week12_24)), by = Week12_24_subgroup ]

```

What is a more elegant approach to do this?