Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ifelse with no else

Tags:

r

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

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

there is no need for else.

How to do it in R? This is my script below which does not work:

attach(iris)

iris2 <- iris
iris2$Species <- ifelse(iris2$Species=='setosa',iris2$Species <- 'regular',iris2$Species <- iris2$Species)
table(iris2$Species)
like image 403
Albert S Avatar asked Feb 23 '17 22:02

Albert S


People also ask

Can you have if without else in R?

Both are fine. You'll find that ifelse gets used a lot more than if in R because it's vectorized. It drops attributes, though, which can cause issues if you're working with more complicated data types.

Can you do else if without else?

else can be omitted for any if statement, there is nothing special in the last if of an if / else if chain.

Is else necessary after if?

No, It's not required to write the else part for the if statement. In fact most of the developers prefer and recommend to avoid the else block.

How do you use Ifelse?

Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false. Use switch to specify many alternative blocks of code to be executed.


1 Answers

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.)

like image 134
Gregor Thomas Avatar answered Sep 21 '22 19:09

Gregor Thomas