1

I am trying to clean some data by chunking my code by using functions.

I have no problem with the following code.

dat <- read_dta('file.dta')

dat <- mutate_at(dat, vars(a,b,c,...,z), list(~ ifelse(. == 9 | . == 99 | . == 999, NA, .)))

With this code, I have no issues. However, I would like to turn it into a function. To do this, I put the following code:

dat <- read_dta('file.dta')

f1 <- function(){
  dat <- mutate_at(dat, vars(a,b,c,...,z), list(~ ifelse(. == 9 | . == 99 | . == 999, NA, .)))

When I do this, the code runs with no errors or warnings. However, the body of function does not do anything to my dataset. Am I missing something here? Any help is much appreciated!

slava-kohut
  • 4,203
  • 1
  • 7
  • 24

1 Answers1

1

Your function cannot modify the object in place. That's how R works. You need something like this:

dat <- read_dta('file.dta')

f1 <- function(x){
  mutate_at(x, vars(a,b,c,...,z), list(~ ifelse(. == 9 | . == 99 | . == 999, NA, .)))}

dat <- f1(dat)
slava-kohut
  • 4,203
  • 1
  • 7
  • 24