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
______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.