rdata.table

R, sorting a data.table with a given user input


This is my data.

dt<-as.data.table(matrix(data = sample(c(paste0(sample(letters, 9), 1:120), round(runif(5) * 100)), 120, replace = TRUE),nrow = 20,ncol = 6,byrow = FALSE))

All or some columns are either number, alphabets or mix of both. I need to sort the the data based on input of which columns i.e. whether for only 1 column or 2 columns together or more.

lets assume this is the user input currently

fromexcel<-c("V1", "V2", "V3")
  1. But the code needs to be such that it is dynamic and considers more columns if asked.
  2. columns asked from user need not be ordered but can be c("V5", "V1") this way as well.

I have always used gtools::mixedsort() but anything else efficient is welcome.

this post can be referenced if you find this useful. sorting a very large dataset in R

Thanks.


Solution

  • One option:

    dt[do.call(order, mget(fromexcel))]
    

    But as r2evans explains in comments the canonical data.table way would be (this sorts the table in place):

    setorderv(dt, fromexcel)