I would like to apply an ifelse function looping through 2 vectors and then based on the condition update the columns of a data table. I'm looking for a solution which can work on large number of columns.
I'm demonstrating the problem through a toy dataset mtcars
.
library(data.table)
mtcars <- data.table(mtcars)
Now, I would like to limit the values for some of the columns and replace the values of the corresponding columns with the defined limits. But the below code is giving me weird results.
limitlist <- list(c("hp", 300), c("disp", 450.0))
cols <- sapply(limitlist, "[[", 1)
lims <- sapply(limitlist, "[[", 2)
for (i in length(limitlist)) mtcars[, c(cols) := lapply(.SD, function(x){ifelse(x[i] > lims[i], lims[i], x[i])}), .SDcols = cols]
My desired output:
range(mtcars$hp)
[1] 52 300
range(mtcars$disp)
[1] 71.1 450.0
I'm new to data.table syntax so might be a dumb error. Any help on this is highly appreciated.
mydata$arr_time <- pmin(2000, mydata$arr_time)
? - Andrew Gustarc(col) :=
doesn't work either. - DebbiesetDT(mtcars)
throws an error: Can not convert 'mtcars' to data.table by reference because binding is locked. It is very likely that 'mtcars' resides within a package (or an environment) that is locked to prevent modifying its variable bindings. Try copying the object to your current environment, ex: var <- copy(var) and then using setDT again. - Uwe