Is there a way to multiply each variable (a
, b
, c
) value in df
by its corresponding group mean and divide by its standard deviation in df_summary
. I would like to do it without hardcoding? Thanks
library(tidyverse)
set.seed(1)
df <- tibble(a = rnorm(10),
b = rnorm(10),
c = rnorm(10)) %>%
mutate(group = c(rep(1, 5), rep(2, 5)),
.before = "a")
df_summary <- df %>%
group_by(group) %>%
summarise(across(.cols = everything(),
.fns = list(mean = mean,
sd = sd),
.names = "{.col}_{.fn}")) %>%
ungroup()
df
#> # A tibble: 10 × 4
#> group a b c
#> <dbl> <dbl> <dbl> <dbl>
#> 1 1 -0.626 1.51 0.919
#> 2 1 0.184 0.390 0.782
#> 3 1 -0.836 -0.621 0.0746
#> 4 1 1.60 -2.21 -1.99
#> 5 1 0.330 1.12 0.620
#> 6 2 -0.820 -0.0449 -0.0561
#> 7 2 0.487 -0.0162 -0.156
#> 8 2 0.738 0.944 -1.47
#> 9 2 0.576 0.821 -0.478
#> 10 2 -0.305 0.594 0.418
df_summary
#> # A tibble: 2 × 7
#> group a_mean a_sd b_mean b_sd c_mean c_sd
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 1 0.129 0.961 0.0381 1.50 0.0812 1.20
#> 2 2 0.135 0.669 0.460 0.465 -0.349 0.705
Created on 2021-11-23 by the reprex package (v2.0.1)