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.
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))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With