Displaying 3 results from an estimated 3 matches for "df_test".
Did you mean:
dd_test
2024 May 24
1
dplyr, group_by and selective action according to each group
...g 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"]])
??????????...
2024 May 24
1
dplyr, group_by and selective action according to each group
...functions get sufficiently
complicated or numerous, it may be useful to store them in a named list and
use the names to call them in some sort of loop. Here I have just used your
anonymous functions in the list, but of course you could have used already
existing functions instead.
## your example
df_test <- data.frame( x1=1:9, x2=1:9, gr=rep(paste0("gr",1:3),each=3))
## function list with the relevant names
funcs <- list(gr1 = \(x)x+1, gr2 = \(x)0, gr3 = \(x)x+2)
## Alternatively you could do this if you had many different functions:
## funcs <- list(\(x)x+1, \(x)0, \(x)x+2)
##...
2024 May 25
1
dplyr, group_by and selective action according to each group
...functions get sufficiently
complicated or numerous, it may be useful to store them in a named list and
use the names to call them in some sort of loop. Here I have just used your
anonymous functions in the list, but of course you could have used already
existing functions instead.
## your example
df_test <- data.frame( x1=1:9, x2=1:9, gr=rep(paste0("gr",1:3),each=3))
## function list with the relevant names
funcs <- list(gr1 = \(x)x+1, gr2 = \(x)0, gr3 = \(x)x+2)
## Alternatively you could do this if you had many different functions:
## funcs <- list(\(x)x+1, \(x)0, \(x)x+2)
##...