0

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")
markus
  • 25,843
  • 5
  • 39
  • 58
user3507584
  • 3,246
  • 5
  • 42
  • 66

1 Answers1

1

From a compilation of various SO answers, the following seems to be working for me:

wt_correction <- function(.df = NULL, .wt_var = NULL){
  .df[cyl==4, (.wt_var) := get(.wt_var)*2]
  .df[cyl==6, (.wt_var) := get(.wt_var)*3]
  .df[cyl==8, (.wt_var) := get(.wt_var)*0.5]
  return(.df)
}

Source 1 (Matt Dowle's answer)

Source 2

zack
  • 5,205
  • 1
  • 19
  • 25