简体   繁体   English

在 R 中使用 ifelse

[英]Using ifelse in R

I am trying to code the following statement in R with if and ifelse .The sample data is trial and x,y,and z are columns of trial).我正在尝试使用ififelse在 R 中编写以下语句。示例数据是试验,x、y 和 z 是试验列)。

Statements to be coded要编码的语句

if (x>0) {
      if (y>0) {
          l=2
       }else{
           l=5
       }
      if (z>0) {
          m=l+2
       }else{
           m=5
       }
}

The R code using ifelse使用 ifelse 的 R 代码

trial$l<-with(trial, ifelse((x>0 &y>0),2,ifelse((x>0 &y<=0),5,???)))
trial$m<-with (trial,ifelse((x>0 &z>0),l+2,ifelse((x>0 &z<=0),5,???)))

where, ???哪里, ??? specifies that there are no values according to the above statement.指定没有根据上述语句的值。 In other words for x<0 and y there are no values.换句话说,对于x<0 and y ,没有值。

Next, I use combination of if and ifelse to see that works:接下来,我使用 if 和 ifelse 的组合来查看是否有效:

if(trial$z>0){
    trial$l<-with(trial, ifelse(y>0,2,5))
    trial$m<-with(trial, ifelse(z>0,l+2,5))
}

This code is ok but there is a warning message (since z is a column vector)此代码没问题,但有一条警告消息(因为z是列向量)

In if (trial$z>0){
the condition has length>1 and only the first element will be used

I want to focus only on using ifelse since I am dealing with only vector.我只想专注于使用ifelse因为我只处理向量。 But, I have no luck in this regard.但是,我在这方面没有运气。 Any idea?任何的想法?

If you want to use ifelse and nest things you could do something like this如果你想使用 ifelse 和嵌套的东西,你可以做这样的事情

test <- data.frame(x = 2, y = 5, z = 3)
with(test, ifelse(z > 0 & x > 0 | y > 3, "yes", "no"))

In this case you're using logical operators to guard the output.在这种情况下,您使用逻辑运算符来保护输出。 You'll still get "no" if z <= 0 , but you can deal with that pretty easily.如果z <= 0 ,您仍然会得到“否”,但您可以很容易地处理它。

with(test, ifelse(z > 0, ifelse(x > 0 | y > 3, "yes", "no"), NA))

Nested ifelse statements can get hard to follow in any language, so consider matching or switch statements if you end up with more than 3 of them.嵌套的ifelse语句在任何语言中都很难遵循,因此如果最终得到 3 个以上的语句,请考虑匹配或 switch 语句。

I would use transform twice for example:例如,我会使用transform两次:

trial <- data.frame(x=c(-1,1,2),y=c(1,-2,3),z=c(1,-5,5))
trial <- transform(trial,l = ifelse(x>0,ifelse(y > 0,2,5),NA))
transform(trial,m = ifelse(x>0,ifelse(z>0,l+2,5),NA))

   x  y  z  l  m
1 -1  1  1 NA NA
2  1 -2 -5  5  5
3  2  3  5  2  4

Note that I assign NA for case x < 0. You can use a one transform like this for example:请注意,我为案例 x < 0 分配了 NA。例如,您可以使用这样的单变换:

trial <- data.frame(x=c(-1,1,2),y=c(1,-2,3),z=c(1,-5,5))
transform(trial,l <- ifelse(x>0,ifelse(y > 0,2,5),NA),
                         m = ifelse(x>0,ifelse(z>0,l+2,5),NA))
  x  y  z c.NA..5..2.  m
1 -1  1  1          NA NA
2  1 -2 -5           5  5
3  2  3  5           2  4

But personally I would prefer the first one for readability besides the fact you need maybe change column names.但就个人而言,除了您可能需要更改列名这一事实之外,我更喜欢第一个以提高可读性。

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

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