How to wrap "downward sort in data table" in a function?

After viewing Sort the data table in ascending / descending order

I would like to wrap either

X <- X[order(Year, MemberID, -Month)]

or

X[,Month:=-Month]
setkey(X,Year,MemberID,Month)
X[,Month:=-Month]

To a function like d.setkey(data, key)

However, it seems that orderand :=rhs only accept column names instead of the symbol, I do not know how to pass an argument?

+4
source share
1 answer

You can use get:

DT[, "Month" := -get("Month"),with=TRUE]

Or:

DT[,`:=`("Month"=-get("Month"))]

Or more general using expression:

expr <- substitute(x := -x,  list(x=as.name("Month")))
DT[,eval(expr)]
+4
source

All Articles