且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

满足条件时如何添加包含特定值的列?

更新时间:2023-12-01 14:51:58

在取了'x'和'y'的差后,可以用sign创建数据集中的新变量,得到sign值,使用levels和指定的相应labels将其转换为factor

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


或带有case_when

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

数据

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