rgroup-bymeanquartile

R Mean of multiple groups by quartiles


I have a dataframe with different variables, e.g.: x1, x2 and so on. I created quartiles based on one variable (BE) with the following code:

Quantile_Var <- Var%>% mutate(Quartile = ntile(BE, 5))

Now I want to see the means of each variables (x1, x2...) by quartiles. I tried to use the following code, but it gives me too many information since I only need the means. How to edit the code so R only gives me the means?

Quantile_Testvar %>% split(.$quartile) %>% map(summary)`

It's probably completly easy, unfortunaly I have struggles to do so


Solution

  • You can use output from ntile as a group and get the average value for all the x variables.

    library(dplyr)
    
    Quantile_Var <- Var %>% 
                      group_by(Quartile = ntile(BE, 5)) %>%
                      summarise(across(starts_with('x'), mean, na.rm = TRUE))