ifelse with no else

前端 未结 2 1537
面向向阳花
面向向阳花 2020-12-30 07:32

Basically in SAS I could just do an if statement without an else. For example:

if species=\'setosa\' then species=\'regular\';

there is no

相关标签:
2条回答
  • 2020-12-30 08:22

    A couple options. The best is to just do the replacement, this is nice and clean:

    iris2$Species[iris2$Species == 'setosa'] <- 'regular'
    

    ifelse returns a vector, so the way to use it in cases like this is to replace the column with a new one created by ifelse. Don't do assignment inside ifelse!

    iris2$Species <- ifelse(iris2$Species=='setosa', 'regular', iris2$Species)
    

    But there's rarely need to use ifelse if the else is "stay the same" - the direct replacement of the subset (the first line of code in this answer) is better.


    New factor levels

    Okay, so the code posted above doesn't actually work - this is because iris$Species is a factor (categorical) variable, and 'regular' isn't one of the categories. The easiest way to deal with this is to coerce the variable to character before editing:

    iris2$Species <- as.character(iris2$Species)
    iris2$Species[iris2$Species == 'setosa'] <- 'regular'
    

    Other methods work as well, (editing the factor levels directly or re-factoring and specifying new labels), but that's not the focus of your question so I'll consider it out of scope for the answer.


    Also, as I said in the comments, don't use attach. If you're not careful with it you can end up with your columns out of sync creating annoying bugs. (In the code you post, you're not using it anyway - the rest runs just as well if you delete the attach line.)

    0 讨论(0)
  • 2020-12-30 08:26

    I would recommend looking at the base R documentation for help with this. You can find the documentation of if, else, and ifelse here. For use of if and else, refer to ?Control.

    Regular control flow in code is done with the basic if and else statements, as in most languages. ifelse() is used for vectorized operations--it will return the same shape as your vector based on the test. Regular if and else expressions do not necessarily have those properties.

    0 讨论(0)
提交回复
热议问题