jeudi 17 décembre 2020

dplyr r turn first line-item text KPI to NA by dimension

Here is the dataframe starwars from the dplyr library in R. What I'm trying to do is turn the first line item of mean_height and median_height of the group by to NA.

So for example, if you ran the code snippet below, I'd want mean_height = NA and median_height at the line item of hair_color = auburn and skin_color = fair. After that particular group_by, mean_height = NA and median_height at the line item of hair_color = black and skin_color = blue, grey, and so on!

I'd prefer the solution in dplyr

Thanks so much for the help!

library(dplyr)

dimensions_groupBy <- c("hair_color", "skin_color")
measures_choices <- c("height", "mass")
aggregating_choices <- list("mean" = mean, "median" = median)

starwars %>% 
  group_by(across(all_of(dimensions_groupBy))) %>% 
  summarise(across(all_of(measures_choices),
                   aggregating_choices,
                   .names = "{fn}_{col}"))

Aucun commentaire:

Enregistrer un commentaire