对多个条件使用if else语句 [英] Using if else statement for multiple conditions

查看:331
本文介绍了对多个条件使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆