I want to update values in some specified columns of a data table based on external values from another data table.
I know how to make this variable a variable, but I need a more efficient solution that I can automate, perhaps using lapply
The UPDATE . My dataset (equivalent mtcarsin the example below) contains other columns that I do not want to update.
For a reproducible example, first run this piece of code
library(data.table)
data(mtcars)
var <- c("mpg","disp","hp")
Decimal <- c(1,3,2)
DT <- cbind.data.frame(var, Decimal)
setDT(DT)
setDT(mtcars)
My code updating column by column
mtcars[, mpg := mpg / 10 ^ DT[var=="mpg", Decimal] ]
mtcars[, disp := disp / 10 ^ DT[var=="disp", Decimal] ]
mtcars[, hp := hp / 10 ^ DT[var=="hp", Decimal] ]
This code works great and gives the desired result.
Desired Result
The first line is mtcarsused like this:
> mpg disp hp
> 1: 21.0 160 110
and now it looks like this:
> mpg disp hp
> 1: 2.10 0.160 1.10
function, lapply ..