user53020
user53020

Reputation: 889

Using if else statement for multiple conditions

Sample data:

x<-runif(100, min=0, max=1)
y<-runif(100, min=0, max=1)
dif<-x-y
dat<-data.frame(x,dif)

What I want to do is to create another column in data frame dat called suit. If x is less than 0.15 and dif is less than 0, than suit should have a value of 3. If x is less than 0.15 and dif is greater than 0, than suit should have a value of 2 and if dif is greater than 0, than suit has value of 1.

This is the code that I am prepared.

if(dat$x<0.15 & dat$dif<0){
   dat$suit<-3
} else {
if(dat$x>=0.15 & dat$dif<0){
   dat$suit<-2  
} else {
  dat$suit<-1  
 }
}

It gives all the values of dat$suit as 1. I am not sure what I am doing wrong here.

Thank you for your help.

Upvotes: 9

Views: 59937

Answers (2)

Matthew Lundberg
Matthew Lundberg

Reputation: 42649

The problem with your statement is that if only checks the first element of the expression tested -- you should have received a warning. ifelse is vectorized.

In addition, you can perform the tests in the reverse order for a simpler, equivalent expression:

with(dat,
     ifelse(dif >= 0 , 1 , ifelse(x < 0.15, 3, 2))
)

Upvotes: 5

akrun
akrun

Reputation: 887118

This can be done using either ifelse

with(dat, ifelse(x < 0.15 & dif <0, 3, ifelse(x > 0.15 & dif < 0, 2, 1)))

Or

with(dat, as.numeric(factor(1+4*(x < 0.15 & dif < 0) + 2*(x>=0.15 & dif < 0))))

Upvotes: 11

Related Questions