Add multiple new columns to a data table

Viewed 286

I have a set of data and I need to add multiple extra columns to rank the existing data. I am doing this by adding one extra column at a time but I was hoping for a more efficient way by passing in the columns as a character vector? Here is a simple example:

require(data.table)
dt <- data.table(x = rnorm(10),
                 y = rnorm(10))

dt[, ":=" (rank_x = rank(x, ties.method = "min"),
           rank_y = rank(y, ties.method = "min"))]

The ranking method is the same in all cases so I was hoping to use something like

cols <- c("x", "y")

dt[, cols := lapply(.SD, function(x) rank(x, ties.method = "min")), .SDcols = cols]
1 Answers
Related