Search code examples
rvariablestransformrecode

recode into same variable


I have a big set of survey data containing 110 variables. Some answers range from 1 to 5, where 1 is best and 5 is worst. For analysis I would like to invert that, where 5=1, 4=2, 3=3, 2=4, and 1=5.

If I put it into an object it works:

x_inv <- recode(x, "5=1; 4=2;3=3;2=4; 1=5")

Yet if I do it that way, I will end having 110 objects. Thus I am looking for a way to change that variable directly within the data frame.

That for I tried just recode:

recode(x, "5=1; 4=2;3=3;2=4; 1=5")

That works if you look at that variable, yet if you ask for the mean, it hasn't changed, eg from 1.82 to 4.18.

Does anyone know how to do that?


Solution

  • Here's a more verbose illustration of how I would do it.

    library(car) #* contains the recode function
    
    #* Construct a sample data set
    DFrame <- lapply(1:10, 
                     function(i) sample(1:5, 15, replace = TRUE))
    DFrame <- as.data.frame(DFrame)
    set.seed(pi)
    DFrame$id = LETTERS[1:15]
    DFrame <- DFrame[, c(11, 1:10)]
    names(DFrame)[-1] <- paste0("Var", 1:10)
    
    DFrame
    
    #* Identify variables that need to be recoded.
    #* Searches for any variable that has only values in 1:5
    var_to_reverse <- 
      vapply(DFrame, 
             function(x) all(x %in% 1:5),
             logical(1))
    
    #* In your case, I think recode is a bit of overkill
    #* Here's how to do it with 6 - x
    DFrame2 <- DFrame
    DFrame2[, var_to_reverse] <- 
      lapply(DFrame2[, var_to_reverse, drop = FALSE],
             function(x) 6 - x)
    
    #* Here's how to do it with recode, if you have a more complex situation.
    DFrame3 <- DFrame
    DFrame3[, var_to_reverse] <- 
      lapply(DFrame3[, var_to_reverse, drop = FALSE],
             recode, 
             recodes = "5=1; 4=2;3=3;2=4; 1=5")
    
    #* confirm that both methods provide the same result.
    identical(DFrame2, DFrame3)