0

I am trying to write a function for recoding variables (as I have to perform the same task several times).

Can anyone please tell my why this code fails?

mydata <- data.frame(s_18 = c(1,2,3,4,5,4,5,4,3,4,3,2,1,2,3,1,2,3,4,5,4,3,2,1,2,1,2,3,1), 
                     s_19 = c(2,1,2,3,1,2,3,4,5,4,3,2,1,2,1,2,3,1,5,4,2,3,1,2,3,2,1,4,5))

# Recoding from numeric into character (works fine)
mydata$s_18new[mydata$s_18 == 1] <- "Agree"
mydata$s_18new[mydata$s_18 == 2] <- "Partly Agree"
mydata$s_18new[mydata$s_18 == 3] <- "Neutral"
mydata$s_18new[mydata$s_18 == 4] <- "Partly disagree"
mydata$s_18new[mydata$s_18 == 5] <- "Disagree"

mydata$s_18new

# But I have to perform this task about 50 times - so I thought a function would be a good solution
my_function <- function(new_var_name, old_var_name) {
  mydata$new_var_name[mydata$old_var_name == 1] <- "Agree"
  mydata$new_var_name[mydata$old_var_name == 2] <- "Partly Agree"
  mydata$new_var_name[mydata$old_var_name == 3] <- "Neutral"
  mydata$new_var_name[mydata$old_var_name == 4] <- "Partly disagree"
  mydata$new_var_name[mydata$old_var_name == 5] <- "Disagree"
}

my_function(s_19new, s_19)
Metods
  • 65
  • 5

1 Answers1

1

You can also use sapply to do this, requires less typing:

# create a dictionary of mapping
temp <- list('1'='Agree', '2'='Partly Agree', '3'='Neutral', '4'='Partly Disagree', '5'='Disagree')

# map the values
mydata$s_19new <- sapply(mydata$s_19, function(x) temp[[as.character(x)]])
YOLO
  • 20,181
  • 5
  • 20
  • 40