From 0c98041fb7e45b613671d1eda2658e1fa1aa65cb Mon Sep 17 00:00:00 2001 From: Anil Goyal <73267890+anilyayavar@users.noreply.github.com> Date: Sun, 28 Jul 2024 11:39:39 +0530 Subject: [PATCH] when you have groups of columns when you have groups of columns that you want to compute with simultaneously. --- iteration.qmd | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/iteration.qmd b/iteration.qmd index 62090c688..bbff172b5 100644 --- a/iteration.qmd +++ b/iteration.qmd @@ -393,7 +393,27 @@ df_long |> summarize(mean = weighted.mean(val, wts)) ``` -If needed, you could `pivot_wider()` this back to the original form. +If needed, you could `pivot_wider()` this back to the original form. + +This problem was actually solved on StackOverflow much earlier to release of 2nd edition. + +```{r} +df_paired |> + summarise( + across( + .cols = ends_with("val"), + .fns = ~ weighted.mean(., get(str_replace( + cur_column(), "val", "wts" + ))), + .names = '{str_remove(col, "_val")}' + ) + ) + +#> # A tibble: 1 × 4 +#> a b c d +#> +#> 1 0.180 0.199 -0.208 -0.746 +``` ### Exercises