Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using if else statement for multiple conditions

Tags:

r

if-statement

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.

like image 472
user53020 Avatar asked Apr 23 '16 15:04

user53020


1 Answers

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))))
like image 64
akrun Avatar answered Sep 28 '22 06:09

akrun