[R] dplyr, group_by and selective action according to each group

Laurent Rhelp |@urentRHe|p @end|ng |rom |ree@|r
Fri May 24 21:35:29 CEST 2024


Dear RHelp-list,

    Using dplyr and the group_by approach on a dataframe, I want to be 
able to apply a specific action according to the group name. The code 
bellow works, but I am not able to write it in a more esthetic way using 
dplyr. Can somebody help me to find a better solution ?

Thank you

Best regards

Laurent

df_test <- data.frame( x1=1:9, x2=1:9, gr=rep(paste0("gr",1:3),each=3))
df_test  <-  df_test %>% dplyr::group_by(gr) %>%
   group_modify(.f=function(.x,.y){
     print(paste0("Nom du groupe : ",.y[["gr"]]))
     switch(as.character(.y[["gr"]])
            , gr1 = {.x[,"x1"] <- .x[,"x1"]+1}
            , gr2 = {.x[,"x1"] <- 0}
            , gr3 = {.x[,"x1"] <- .x[,"x1"]+2}
            , {stop(paste0('The group ',.y[["gr"]]," is not taken into 
account"))}
     )
     return(.x) }) %>% ungroup()

df_test



More information about the R-help mailing list