Doing absolute descending data.table type through function?

I would like to do absolute top-down sorting , i.e. sort, ignoring the sign, for example, 5, -2, 1) of mine data.table, passing sort.field to the function.

I looked at the descending sort , but in my efforts I get errors or I transform the sign of my variable and do not sort it correctly.

It works:

library(data.table)
DT <- data.table(id = c("a","b","z"), 
                 score = c(1, 5, -2))
DT1 <- copy(DT)

#doing sort direct works
DT1 <- DT1[order(-abs(score))] 
# i.e. b, Z, a

But when passing the parameter, I cannot find the correct syntax (mathematical errors, j must be provided, etc.)

#in function
sort.field = "score"

sortme <- function(dt, sort.field){

  dt <- dt[order(-abs(sort.field))]  
}

DT2 <- sortme(DT, sort.field)
#  ERROR get non-numeric argument to maths function as it sees string

I tried various ratings, as.name, c = F, etc.

   dt <- dt[, order(-abs(as.name(sort.field))]  

   # even
    expr <- substitute(x := -abs(x),  list(x=as.name(sort.field)))
    dt<- dt[,eval(expr)]

DT3 <- DT[,eval(expr)] # changes all to negative
DT4 <- DT[order(eval(expr))] # DT not happy

Please remove me from my misery! Many thanks.

P.S. setorderv() . , , , setorderv, temp, .

: . data.frames, , . abs() , . , data.table, setorderv().

+4
2

:

sort.field = "score"

sortme <- function(dt, sort.field) dt[order(-abs(dt[[sort.field]]))]

sortme(DT, sort.field)
#   id score
#1:  b     5
#2:  z    -2
#3:  a     1

, , abs, ERROR get non-numeric argument to maths function as it sees string

+3

eval(as.name())

 sort.field = "score"
 sort_me <- function(dt, sort.field){
  dt[order(-abs(eval(as.name(sort.field))))]
 }
 sort_me(DT, sort.field)
 #   id score
 #1:  b     5
 #2:  z    -2
 #3:  a     1
+3

All Articles