Passing Variable Arguments to a Function

Hi All ,

Trying to write a function that takes multiple and variable arguments (Column names) then orders the data frame based on selected columns.

Works:

colSort1 <- function(data,col1,col2){
 ord<-order(data[,col1],data[,col2],decreasing=TRUE)
  sorted <-data[ord,]
  invisible(sorted)
  }

test1<-tcolSort1(mtcars,"disp","hp")

Does not work

colSort <-function(data,...,decreasing=TRUE){
  l1<-list(...)
  ord<-order(glue::glue("data","[,{l1}]"))
  sorted <-data[ord]
  invisible(sorted)
}

t1<-colSort(mtcars,"disp","hp") 

The dplyr alternative could be arrange and all_of but trying it get a hang of ( ...) in functions.

Thanks

You can use do.call to pass a list of arguments to order. The key is you need a step in between because order requires vector arguments rather than the column names supplied in ...

Below should work:

colSort <-function(data,...,decreasing=TRUE){
  # Get list of arguments from ...
  l1<-list(...)
  
  # Convert column names to list of vectors to use for ordering
  l2 <- lapply(l1, function(x){data[[x]]})
  
  # Add decreasing argument as named element of list
  l2$decreasing <- decreasing
  
  # Use do.call to pass list of arguments to order
  sort_order <- do.call(order, l2)
  
  # Sort data
  sorted <- data[sort_order,]
  
  invisible(sorted)
}

t1<-colSort(mtcars,"disp","qsec")
1 Like

Hi Sir ,

Thanks for the help and simple explanations !! Highly appreciated.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.