Reputation: 177
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)
Upvotes: 14
Views: 56690
Reputation: 146249
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.
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.)
Upvotes: 32