Using ifelse in R

前端 未结 2 1196
慢半拍i
慢半拍i 2020-12-07 04:32

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

S

2条回答
  •  Happy的楠姐
    2020-12-07 05:25

    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
    

    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.

提交回复
热议问题