Rose
Rose

Reputation: 53

How to use ifelse using mutate to get a new column in R

A simple sample of my data is shown below

   

 Id   x   y   
 12 Yellow  Yellow    
 13 Yellow  Blue      
 10 Blue    Yellow    
 14 Blue    Blue      
 19 Yellow  Yellow    

And I want to get this

Id  x   y   z
12  Yellow  Yellow  Y
13  Yellow  Blue    N
10  Blue    Yellow  N
14  Blue    Blue    N
19  Yellow  Yellow  Y

When x and y are only Yellow, I get Y, else N for the z column

I have tried this, but it does not help me.

dat%>% mutate(z=ifelse(x=="Yellow") & (ifelse(y=="yellow")),"Y","N")

Upvotes: 0

Views: 50

Answers (3)

akrun
akrun

Reputation: 887048

We don't need two ifelse. Also, the ifelse for first and second only had the 'test' condition, without the 'yes' or 'no' i.e. According to ?ifelse, usage is

ifelse(test, yes, no)

In the OP's post, the ifelse got closed after the test condition

ifelse(y=="yellow")
         ^test condition

For multiple elements, instead of ==, can use %in%

dat$z <- c("N", "Y")[Reduce(`&`, lapply(dat[-1], `%in%`, c('yellow', 'Yellow'))) + 1]
dat$z
#[1] "Y" "N" "N" "N" "Y"

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 101247

Here is one base R option without ifelse

transform(
  df,
  z = c("N", "Y")[1 + (rowSums(cbind(x, y) == "Yellow") == 2)]
)

which gives

  Id      x      y z
1 12 Yellow Yellow Y
2 13 Yellow   Blue N
3 10   Blue Yellow N
4 14   Blue   Blue N
5 19 Yellow Yellow Y

Upvotes: 0

Aleiem
Aleiem

Reputation: 226

Does this work?

dat %>% mutate(z=ifelse(x=="Yellow" & y == "Yellow", "Y", "N"))

Or maybe this:

dat %>% mutate(z=ifelse(tolower(x)=="yellow" & tolower(y) == "yellow", "Y", "N"))

Upvotes: 1

Related Questions