samedi 23 avril 2016

R 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.

Aucun commentaire:

Enregistrer un commentaire