1

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.

Laura
  • 13
  • 3

1 Answers1

0

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))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • When I table AntPT, it returns me 0 and 1, but it's the same with AntPSDB. AntPMDB gives me only the number 0. Also, he sum returns me only 0 and 1, and not all the numbers I need. :/ – Laura Apr 10 '20 at 19:38
  • @LauraBeghini From your code, it seems that you are recoding 1 to 1 and 2 to 10 to 0 `recode(e18$AntPT, 1<-1, 0 <- c(2:10))`. Is that right. Or are you saying that there are numbers other than 1 to 10 shhould remain as such – akrun Apr 10 '20 at 19:39
  • 1
    Yes! That's right. That's the recode I want to do. Gonna check it now. – Laura Apr 10 '20 at 19:49
  • The sum returned me the following numbers: 0 3 33 36 39 42. – Laura Apr 10 '20 at 19:53
  • isn't that right. I am not changing other numbers if you check my example data – akrun Apr 10 '20 at 19:53
  • 1
    I understand it now! Thanks. – Laura Apr 10 '20 at 19:59