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.)
sort.field = "score"
sortme <- function(dt, sort.field){
dt <- dt[order(-abs(sort.field))]
}
DT2 <- sortme(DT, sort.field)
I tried various ratings, as.name, c = F, etc.
dt <- dt[, order(-abs(as.name(sort.field))]
expr <- substitute(x := -abs(x), list(x=as.name(sort.field)))
dt<- dt[,eval(expr)]
DT3 <- DT[,eval(expr)]
DT4 <- DT[order(eval(expr))]
Please remove me from my misery! Many thanks.
P.S. setorderv() . , , , setorderv, temp, .
: . data.frames, , . abs() , . , data.table, setorderv().