简体   繁体   English

对多个条件使用if else语句

[英]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 . 我想要做的是在数据框dat创建另一个名为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. 如果x小于0.15且dif小于0,则suit的值应为3.如果x小于0.15且dif大于0,则suit的值应为2,如果dif大于0 ,比suit价值为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. 它将dat$suit所有值都赋予1.我不确定我在这里做错了什么。

Thank you for your help. 谢谢您的帮助。

This can be done using either ifelse 这可以使用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))))

The problem with your statement is that if only checks the first element of the expression tested -- you should have received a warning. 您的陈述的问题是, if只检查测试表达式的第一个元素 - 您应该收到警告。 ifelse is vectorized. ifelse是矢量化的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM