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

后端 未结 2 777
说谎
说谎 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:28

    The new variable in the dataset can be created with sign after taking the difference of 'x' and 'y', get the sign values, convert it to factor with levels and corresponding labels specified

    library(dplyr)
    df1 %>% 
     mutate(z = factor(sign(x - y), levels = c(-1, 0, 1), 
       c('Lower', "Equal", 'Higher')))
    

    Or an option with case_when

    df1 %>%
      mutate(tmp = x - y,
             z = case_when(tmp >0 ~ 'Higher', tmp < 0 ~ 'Lower',
                 TRUE ~ 'Equal'), tmp = NULL)
    

    data

    df1 <- tibble(
        x = c(1,2,3),
        y = c(0,2,4))
    

提交回复
热议问题