且构网

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

如何根据 R 中的条件创建新变量

更新时间:2022-01-30 02:26:12

除了条件之一,即'a'、'b'中的非NA元素,且彼此不相等,所有其他coalesce 满足条件.因此,我们可以通过应用 coalesce

Except for one of the condition, i.e non-NA elements in both 'a', 'b', and they are not equal to each others, all other conditions are met with coalesce. So, we can do a case_when to generate the "multiple_values" based on the last condition and all others by applying coalesce

library(dplyr)
df1 %>%
     mutate(c = case_when(!is.na(a) & !is.na(b) & a != b ~ "multiple_values", 
               TRUE ~ as.character(coalesce(a, b))))
#   a  b               c
#1  1 NA               1
#2  2  3 multiple_values
#3  3  3               3
#4 NA  2               2
#5 NA NA            <NA>

数据

df1 <- structure(list(a = c(1L, 2L, 3L, NA, NA), b = c(NA, 3L, 3L, 2L, 
 NA)), class = "data.frame", row.names = c(NA, -5L))