I am trying to make an operation conditional on the name of a column in a data.table. With below example I try to illustrate what I mean. We have a DT
with two columns carrot and banana. Each of these columns contains values. I want now that the carrot values are multiplied by 2 and that the banana values are divided by 2. My code, however, does not work, because names(.SD)
is a vector of length 2 (names(DT)
). is there a way I can make this work with lapply()
?
carrot <- 1:5
banana <- 1:5
DT <- data.table(carrot, banana)
DT[, lapply(.SD, function(x) if(names(.SD) == 'carrot') {x * 2} else {x / 2}), .SDcols = names(DT)]