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

基于后续随访记录生成新列:R语言dplyr实现需求

用dplyr补充首次随访的缺失数据

Got it, let's work through this problem together. You're looking to fill in incomplete data (marked as "u") from the first encounter (Time = "A") using values from later follow-ups for each individual—and you want to do this with dplyr. Here's a straightforward approach:

第一步:修正并构造示例数据

First, let's clean up the sample data you provided (the Color vector had a typo) so we can test the code:

# 构造完整的示例数据集
ID <- rep(1:4, 2)
Time <- c("A", "A", "A", "A", "B", "B", "B", "B")
Color <- c("u", "u", "red", "red", "green", "blue", "yellow", "u")
df <- data.frame(ID, Time, Color)

第二步:用dplyr实现数据补充

We'll group by each individual (ID), identify valid non-"u" values, and fill in the first encounter's missing data. Here are two reliable methods:

方法1:显式提取有效值并替换

This method makes the logic super clear, which is great for readability:

library(dplyr)

df_filled <- df %>%
  # 按个体分组,确保我们只在同一个ID的记录内处理
  group_by(ID) %>%
  # 为每个ID获取第一个非"u"的Color值,全是"u"则保留"u"
  mutate(valid_color = first(Color[Color != "u"], default = "u")) %>%
  # 首次随访(Time="A")且原Color为"u"时,用有效值替换,否则保留原数据
  mutate(Color_filled = ifelse(Time == "A" & Color == "u", valid_color, Color)) %>%
  # 取消分组,回到常规数据框
  ungroup()

方法2:转换为NA后使用fill函数

If you prefer a more concise approach, converting "u" to NA lets us use dplyr's built-in fill() function:

df_filled <- df %>%
  group_by(ID) %>%
  # 把标记缺失的"u"转换为NA
  mutate(Color = na_if(Color, "u")) %>%
  # 从下往上填充NA(用后续随访的值填补前面的缺失)
  fill(Color, .direction = "up") %>%
  # 如果某个ID全是缺失,把NA换回"u"
  mutate(Color = coalesce(Color, "u")) %>%
  ungroup()

结果验证

Both methods will give you a dataset where:

  • ID 1's first encounter ("A") gets filled with "green" (from Time="B")
  • ID 2's first encounter gets filled with "blue" (from Time="B")
  • ID 3 and 4's first encounters stay "red" (since they weren't missing)
  • ID 4's second encounter remains "u" (no valid value to fill it)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:26:41