Home > Enterprise >  How could I get the mean and mode summary at the same time for a dataframe?
How could I get the mean and mode summary at the same time for a dataframe?

Time:06-05

I have a dataframe with 10 numeric columns and 3 character columns, as a sample I prepare this dataframe:

df <- data.frame(
  name = c("ANCON","ANCON","ANCON", "LUNA", "MAGOLLO", "MANCHAY", "MANCHAY","PATILLA","PATILLA"),
  destiny = c("sea","reuse","sea","sea", "reuse","sea","sea","sea","sea"),
  year = c("2022","2015","2022","2022", "2015","2016","2016","2018","2018"),
  QQ = c(10,11,3,4,13,11,12,23,7),
  Temp = c(14,16,16,15,16,20,19,14,18))

I need to group it by column "name", get the mean summary for columns "QQ" and "Temp", and the mode for columns "destiny" and "year". I could get the mean summary but I couldn´t include the mode

df_mean <- df %>%                 
  group_by(name) %>%
  summarise_all(mean, na.rm = TRUE)

  name    destiny  year    QQ  Temp
  <chr>     <dbl> <dbl> <dbl> <dbl>
1 ANCON        NA    NA   8    15.3
2 LUNA         NA    NA   4    15  
3 MAGOLLO      NA    NA  13    16  
4 MANCHAY      NA    NA  11.5  19.5
5 PATILLA      NA    NA  15    16  

the desired output with the medians is something like this:

     name destiny year   QQ Temp
1   ANCON     sea 2022  8.0 15.3
2    LUNA     sea 2022  4.0 15.0
3 MAGOLLO   reuse 2015 13.0 16.0
4 MANCHAY     sea 2016 11.5 19.5
5 PATILLA     sea 2018 15.0 16.0

How could I do it? Please help

CodePudding user response:

Use across and cur_column. Median would only work with ordinal data, though, and for categorical data like the character columns you have, use mode:

mode <- function(x) {
   x_unique <- unique(x)
   x_unique[which.max(tabulate(match(x, x_unique)))]
}

Then

mode_columns <- c('destiny', 'year')
df %>% 
    group_by(name) %>%
    summarise(
        across(
            everything(),
            ~ if (cur_column() %in% mode_columns) mode(.x) else mean(.x)
        )
    )
# A tibble: 5 × 5
  name    destiny year     QQ  Temp
  <chr>   <chr>   <chr> <dbl> <dbl>
1 ANCON   sea     2022    8    15.3
2 LUNA    sea     2022    4    15  
3 MAGOLLO reuse   2015   13    16  
4 MANCHAY sea     2016   11.5  19.5
5 PATILLA sea     2018   15    16  

UPD: Or you could summarise a bit differently

     summarise(
        across({{mode_cols}}, mode),
        across(!{{mode_cols}}, mean)
    )
  • Related