how to get colname out of summarize

Hello,

Is there a universal way to get the name of the summarized variable into the tibble with results?
After running a command like below:

library(tidyverse)

mtcars |> group_by(cyl) |> summarize("mean"= mean(mpg), "sd"= sd(mpg), "median" = median(mpg))

I get a 3x4 tibble with columns "cyl", "mean", "sd", "median". It is fine, but I would also like to have a column "name" where the values would be the name of the summarized variable (the same for all rows, obviously).

Would be even nicer if I could get a command with summarize where I only mention the variable once (e.g. mpg in the example above).
Can anybody help me here?

Is this the kind of thing you're looking for?

library(tidyverse, warn.conflicts = FALSE)

mtcars |> 
  group_by(cyl) |> 
  summarize(across(mpg, 
                   list("mean" = mean, 
                        "sd" = sd, 
                        "median" = median,
                        "column" = ~as.character(cur_column())),
                   na.rm = T,
                   .names = "{.fn}"))
#> # A tibble: 3 × 5
#>     cyl  mean    sd median column
#>   <dbl> <dbl> <dbl>  <dbl> <chr> 
#> 1     4  26.7  4.51   26   mpg   
#> 2     6  19.7  1.45   19.7 mpg   
#> 3     8  15.1  2.56   15.2 mpg

Created on 2022-07-02 by the reprex package (v2.0.1)

Yes, exactly, thanks :slight_smile: This additional trick with names without prefix is great.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.