R语言如何根据ID1、ID2两列是否非空新增present列
R 实现dataframe新增present列方案
核心逻辑说明
你示例中的空值为""而非NA,因此直接对两列的非空判断逻辑值求和即可完全匹配需求:R中逻辑值TRUE等价于数值1,FALSE等价于数值0,求和结果刚好对应你要的取值。
方案1:tidyverse 实现
library(tidyverse) example <- example %>% mutate( # 直接对非空判断结果求和 present = (ID1 != "") + (ID2 != ""), # 可选:如果两列都为空时不需要保留0,可替换为NA present = if_else(present == 0, NA_real_, present) )
方案2:基础R实现(无需加载第三方包)
# 直接赋值新列 example$present <- (example$ID1 != "") + (example$ID2 != "") # 可选:将两列都为空对应的0替换为NA example$present[example$present == 0] <- NA
内容的提问来源于stack exchange,提问作者McMahok
相关产品推荐
相关产品推荐

