Reputation: 1
I am a beginner in R and I am trying to understand how ifelse
works.
I tried with something simple like:
ifelse(mydataframe$col1==mydataframe$col2 ,
mydataframe$newCol<-TRUE,
mydataframe$newCol<-FALSE
)
mydataframe$col1
and col2
are factors.
In this case my newCol
will be always FALSE
, which is wrong as I verified in this way:
mydataframe$newCol<- mydataframe[mydataframe$col1==mydataframe$col2]
I also don't want to use a for
loop, which is usually slow for what I tried.
What did I do wrong?
Upvotes: 0
Views: 145
Reputation: 61154
As a matter of fact you don't need to use ifelse
, ==
should suffice as in:
mydataframe$newCol <- with(mydataframe, col1 == col2)
It will return a boolean vector.
Upvotes: 2
Reputation: 11543
ifelse()
accepts return values as the 2nd and 3rd parameters (and you are writing assignments).
Try:
mydataframe$newCol <-
with(mydataframe,
ifelse(col1 == col2,
TRUE,
FALSE))
Upvotes: 3