Ifelse without another

Basically in SAS, I can just execute the if statement without else. For instance:

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

not necessary.

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)
+4
source share
2 answers

A couple of options. It's best to just replace it; it's nice and clean:

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

ifelsereturns a vector, so the way to use it in such cases is to replace the column with a new one ifelse. Do not complete the assignment inside ifelse!

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

But there is no need to use ifelseif else remains unchanged. - It is better to replace the direct replacement of the subset (the first line of code in this answer).


New factor levels

, - , iris$Species factor () , 'regular' . - character :

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

( ), , .


, , attach. , , . ( , , , , attach.)

+6

R . if, else ifelse . if else ?Control.

if else, . ifelse() - , , . if else .

0

Source: https://habr.com/ru/post/1670678/


All Articles