r

How to Use ifelse Statements in R


Here is my code and it isn't working. What am I doing wrong?

nmesRAW <- read.csv("nmesUNPROC.csv")
nmesRAW$beltuse <- ifelse(nmesRAW$beltuse == 1, ‘Rarely’, ifelse(nmesRAW$beltuse == 2 ‘Sometimes’, ifelse(nmesRAW$beltuse == 3 ‘Always’)))

Solution

  • I want to replace all 1's with rarely, all 2's with sometimes, and all 3's with always in this column. how do i do that?

    This is how you would do it on your data, using switch():

    nmesRAW$beltuse <- sapply(nmesRAW$beltuse, function(x) switch(x, "1"="Rarely", "2"="Sometimes", "3"="Always"))
    

    With some code example for reproducibility:

    # some random data
    nmesRAW <- c(1,3,1,2,3,3)
    sapply(nmesRAW, function(x) switch(x, "1"="Rarely", "2"="Sometimes", "3"="Always"))
    # output:
    [1] "Rarely"    "Always"    "Rarely"    "Sometimes" "Always"    "Always"
    

    Using ifelse() only

    If you insist on using ifelse() and nothing else (I hope this is not a schoolwork assignment), then your code should look like this:

    nmesRAW$beltuse <- ifelse(nmesRAW$beltuse == 1, 'Rarely', ifelse(nmesRAW$beltuse == 2, 'Sometimes', 'Always'))
    

    The reason your code is giving you these errors is because you're missing a comma in your second nested if-else and also an 'else' statement in your third nested if-else.

    As you can see, it is a bit all over the place when you nest an if-else this way and can quickly get out of hand.

    When you do an ifelse, you will always need:

    The syntax looks like this ifelse(x$var>10, "Large", "Small"). When you nest your ifelse the way you did it, you quickly lose sight of that, and hence the missing commas, and the missing no condition in your last ifelse.