You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中实现某列缺失时取另一表对应列值填充?

实现方法

首先构造可复现的示例关联表:

df <- data.frame(
  ID = 1:5,
  exit1 = c(NA, "01/02/2016", "01/10/2010", NA, "01/01/2016"),
  exit2 = c("31/01/2016", "01/01/2021", "30/09/2019", "31/12/2015", "30/09/2020")
)

方法1:基础R实现

通过逻辑判断直接替换缺失值:

# 把exit1的缺失值替换为同ID对应exit2的值
df$exit1[is.na(df$exit1)] <- df$exit2[is.na(df$exit1)]
# 提取需要的字段得到最终结果
result <- df[, c("ID", "exit1")]

也可以用ifelse函数实现相同逻辑:

df$exit1 <- ifelse(is.na(df$exit1), df$exit2, df$exit1)
result <- df[, c("ID", "exit1")]

方法2:tidyverse(dplyr)实现

使用专门处理缺省值优先级替换的coalesce()函数,语法更简洁:

library(dplyr)

result <- df %>%
  mutate(exit1 = coalesce(exit1, exit2)) %>%
  select(ID, exit1)

如果后续需要做日期计算,建议把字符串格式的日期转为R标准日期格式,可搭配lubridate包处理:

library(dplyr)
library(lubridate)

result <- df %>%
  mutate(
    exit1 = coalesce(dmy(exit1), dmy(exit2))
  ) %>%
  select(ID, exit1)

内容的提问来源于stack exchange,提问作者Besz15

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 05:36:00