在 R 中使用 ifelse [英] Using ifelse in R

查看:27
本文介绍了在 R 中使用 ifelse的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 ififelse 在 R 中编写以下语句.示例数据是试验,x、y 和 z 是试验的列).

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

要编码的语句

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

使用 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, ??? 指定根据上面的语句没有值.换句话说,对于 x<0 和 y 没有值.

where, ??? specifies that there are no values according to the above statement. In other words for x<0 and y there are no values.

接下来,我使用 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))
}

这段代码没问题但是有一个警告信息(因为z是一个列向量)

This code is ok but there is a warning message (since z is a column vector)

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

我只想专注于使用 ifelse 因为我只处理向量.但是,我在这方面没有运气.有什么想法吗?

I want to focus only on using ifelse since I am dealing with only vector. But, I have no luck in this regard. Any idea?

推荐答案

我会使用 transform 两次,例如:

I would use transform twice for example:

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

请注意,我为 case x < 分配了 NA0. 你可以使用一个这样的转换,例如:

Note that I assign NA for case x < 0. You can use a one transform like this for example:

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.

这篇关于在 R 中使用 ifelse的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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