9

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.

0

2 Answers 2

11

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))))
Sign up to request clarification or add additional context in comments.

Comments

5

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))
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.