I have several data tables with the same variable that requires intensive data tidying. I thought on creating a function but I am struggling to pass the variable name, which is shown in both sides of the :=
assignments.
See a MWE with mtcars
where the variable to alter is wt
. I have tried substitute
and eval
but to no avail.
How would I make the code below work? What is missing? Why this one does not work?
DTmtcars <- data.table(mtcars)
wt_correction <- function(.df = NULL, .wt_var = NULL){
.df[cyl==4, .wt_var := .wt_var*2]
.df[cyl==6, .wt_var := .wt_var*3]
.df[cyl==8, .wt_var := .wt_var*0.5]
return(.df)
}
wt_correction(.df = DTmtcars, .wt_var= "wt")