Sushil
January 3, 2026, 5:49am
1
I tried to create a user defined function with input dataset as argument and sort variable, I could not pass multiple variable in sortvar
my_function<-function(indsn, sortvar){
df <-indsn %>% dplyr::select (Subject, exstdtc) %>% arrange({{sortvar}})
return(df)
}
my_data<-my_function(indsn=ex, sortvar=c(Subject,exstdtc))
use strings around your sortvars
sortvar = c("Subject", "exstdtc")
then use
arrange(across(all_of(sortvar)))
for example:
my_function <-function(indsn, sortvar){
df <- indsn %>%
select(all_of(sortvar)) %>%
arrange(across(all_of(sortvar)))
return(df)
}
my_function(mtcars, c("cyl", "disp"))
Sushil
January 4, 2026, 3:43pm
3
Thank you Soo much, Its working.
How to call the macro if I want to do descending in any one the variable or both the variables
my_function(mtcars, c("cyl", "disp"))
you could provide a second list of columns that you want to arrange in descending order and then add a lambda function to across() that will check if the current column is in that list, as follows:
my_function <-function(indsn, sort_vars, desc_vars){
df <- indsn %>%
select(all_of(sort_vars)) %>%
arrange(
across(
all_of(sort_vars),
~ if (cur_column() %in% desc_vars) desc(.) else .
)
)
return(df)
}
my_function(mtcars, c("cyl", "disp"), "disp")
my_function(mtcars, c("cyl", "disp"), "cyl")
my_function(mtcars, c("cyl", "disp"), c("cyl", "disp"))