对多个条件使用if else语句 [英] Using if else statement for multiple conditions
本文介绍了对多个条件使用if else语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
样本数据:
x<-runif(100, min=0, max=1)
y<-runif(100, min=0, max=1)
dif<-x-y
dat<-data.frame(x,dif)
我想要做的是在数据框dat
中创建另一列,称为suit
.如果x
小于0.15并且dif
小于0,则suit
的值应为3.如果x
小于0.15并且dif
大于0,则应小于suit
的值为2,并且dif
大于0,则suit
的值为1.
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.
这是我准备的代码.
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
}
}
它将dat$suit
的所有值都设置为1.我不确定我在这里做错了什么.
It gives all the values of dat$suit
as 1. I am not sure what I am doing wrong here.
谢谢您的帮助.
推荐答案
可以使用ifelse
with(dat, ifelse(x < 0.15 & dif <0, 3, ifelse(x > 0.15 & dif < 0, 2, 1)))
或
with(dat, as.numeric(factor(1+4*(x < 0.15 & dif < 0) + 2*(x>=0.15 & dif < 0))))
这篇关于对多个条件使用if else语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文