ifelse question, return original value from data frame

egfp

New Member
#1
Hi all,

I am trying to replace values in a data frame using the 'ifelse' function and I am having some trouble. I want to set up a statement so that if the test is false it returns whatever value was there originally.

For example if I have data frame 'X' with values: 1/1, 1/1, 2/2, 3/3
I want to replace all "1/1" with "4/4" and leave everything else as the original value so that the result looks like 4/4, 4/4, 2/2, 3/3

ifelse(X=="1/1","4/4",???)

I appreciate your help!
 

Dason

Ambassador to the humans
#3
Is there a particular reason you're using ifelse? It seems like something that's better suited for just using a logical comparison as your index. For a quick example
Code:
x <- 1:9
x > 5
x[x > 5] <- 9
That changes any value in x that is greater than 5 to be 9. You should be able to modify this to accomplish your goal.
 

Link

Ninja say what!?!
#5
For example if I have data frame 'X' with values: 1/1, 1/1, 2/2, 3/3
I want to replace all "1/1" with "4/4" and leave everything else as the original value so that the result looks like 4/4, 4/4, 2/2, 3/3
X <- ifelse(X=="1/1","4/4", X)


PS. Though my way works, I like Dason's way more.
 

egfp

New Member
#6
Thanks...both of these methods work pretty well but for data frames but i just realized I am using a factor which once again is causing some trouble. I have included a snippet below (basically same as the example in the original post except I want to change "s/l" to "l/s".

> xtest
[1] s/l s/s l/s s/l
Levels: l/s s/l s/s

> ifelse(xtest=="s/l","l/s",xtest)
[1] "l/s" "3" "1" "l/s"

I am not sure why it returns "3" and "1" instead of the value itself. any thoughts?
 
Last edited:

Dason

Ambassador to the humans
#7
It has to do with how factors are internally stored in R.
Code:
?factor
?labels
?levels
Those should shed some light on that for you.
 

TheEcologist

Global Moderator
#8
You can also try to force xtest to behave as a character. By doing this.
Code:
#your problem reproduced
xtest=as.factor(c("s/l","s/s", "l/s", "s/l"))
ifelse(xtest=="s/l","l/s",xtest)
#your problem solved but elements of xtest are now a characters
ifelse(xtest=="s/l","l/s",as.character(xtest))
#your problem solved retaining elements of xtest as as factors
as.factor(ifelse(xtest=="s/l","l/s",as.character(xtest)))
 

trinker

ggplot2orBust
#9
I HAVE HAD similar problems with factors but the Ecologist's suggestion with as.character() usually works. If not a method(though it may be inefficient) is to use the recodeVar() function from the (I think) by package.