rrecodeinvalid-argument

Recode variables in R returns invalid


I'm trying to recode this variable, after transforming it in numeric:

 e18$AntPT <- recode(e18$AntPT, 1 <- 0, 0 <- c(2:10))

but it returns

 Error in 1 <- 0: invalid (do_set) left-hand side to assignment

Also, the final result should include these 3 parts of the code:

e18$AntPT <- as.numeric(e18$Q1501)

e18$AntPT <- recode(e18$AntPT, 1<-1, 0 <- c(2:10))



e18$AntPSDB <- as.numeric(e18$Q1505)

e18$AntPSDB <- recode(e18$AntPSDB, 10<-1, 0 <- c(2:10))



e18$AntPMDB <- as.numeric(e18$Q1502)

e18$AntPMDB <- recode(e18$AntPMDB, 100<-1, 0 <- c(2:10))

The last thing I have to do is:

e18$Ant_Part <- (e18$AntPT + e18$AntPSDB + e18$AntPMDB)

The final result of this sum must give me the numbers 0, 1, 10, 11, 100, 101, 110, 111 - which one of the numbers give me a different interpretation of my initial question.


Solution

  • If there are other numbers in the column and want to change only specific numbers

    -before

    e18
    #  AntPT AntPSDB AntPMDB
    #1     1       1     100
    #2     2      14       1
    #3     4       2       2
    #4     3      15     105
    #5     1       7      24
    #6     2      10       7
    #7     3      11       8
    

    Now, we loop over the columns of interest with lapply and replace the values in the column to 0 where they are from 2 to 10

    e18[c("AntPT", "AntPSDB", "AntPMDB")] <- lapply(e18[c("AntPT", 
      "AntPSDB", "AntPMDB")], function(x) replace(x, x %in% 2:10, 0))
    

    and the specific numbers in columns 'AntPSDB', 'AntPMDB' (10, 100) to 1

    e18$AntPSDB[e18$AntPSDB == 10] <- 1
    e18$AntPMDB[e18$AntPMDB == 100] <- 1
    

    -after

    e18
    #  AntPT AntPSDB AntPMDB
    #1     1       1       1
    #2     0      14       1
    #3     0       0       0
    #4     0      15     105
    #5     1       0      24
    #6     0       0       0
    #7     0      11       0
    

    and then do the sum

    e18$Ant_Part <- (e18$AntPT + e18$AntPSDB + e18$AntPMDB)
    

    data

    e18 <- data.frame(AntPT = c(1, 2, 4, 3, 1, 2, 3),
                       AntPSDB = c(1, 14, 2, 15, 7, 10, 11),
                       AntPMDB = c(100, 1, 2, 105, 24, 7, 8))