【问题标题】:Using if else statement for multiple conditions对多个条件使用 if else 语句
【发布时间】:2016-04-23 15:21:12
【问题描述】:

样本数据:

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。

这是我准备的代码。

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。我不确定我在这里做错了什么。

感谢您的帮助。

【问题讨论】:

    标签: r if-statement


    【解决方案1】:

    这可以使用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))))
    

    【讨论】:

      【解决方案2】:

      您的语句的问题是if 只检查测试表达式的第一个元素——您应该收到警告。 ifelse 被矢量化了。

      此外,您可以以相反的顺序执行测试以获得更简单、等效的表达式:

      with(dat,
           ifelse(dif >= 0 , 1 , ifelse(x < 0.15, 3, 2))
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-06
        • 2015-07-08
        • 1970-01-01
        • 2018-09-24
        • 2020-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多