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
  • 24,556
  • 5
  • 34
  • 51
user3507584
  • 2,881
  • 5
  • 36
  • 56

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
  • 4,835
  • 1
  • 18
  • 25