How to add a column that contains specific values when criteria is met?

后端 未结 2 780
说谎
说谎 2021-01-26 01:29

I have a dataframe:

tibble{
x = c(1,2,3)
y = c(0,2,4)
}

I want to add a NEW variable "z" that will be:

z = c("Lower         


        
2条回答
  •  有刺的猬
    2021-01-26 02:18

    A base R option

    within(df,z <- c("Lower", "Equal", "Higher")[sign(y-x)+2])
    

    which gives

    # A tibble: 3 x 3
          x     y z     
        
    1     1     0 Lower
    2     2     2 Equal
    3     3     4 Higher
    

提交回复
热议问题