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

如何用同组非NA值填充数据框Tumor_Sample_Barcode_pre列缺失值

问题描述

在数据框df_NA中,Tumor_Sample_Barcode_post列的样本值(如s_C_VWPHV0_P002_d)重复出现,对应Tumor_Sample_Barcode_pre列同组应匹配相同的非NA标签,但当前存在NA缺失值。尝试以下两段代码均未生效:

无效代码示例

df_NA %>% group_by(Tumor_Sample_Barcode_post) %>% dplyr::mutate(Tumor_Sample_Barcode_pre = replace_na(Tumor_Sample_Barcode_pre, !is.na(Tumor_Sample_Barcode_pre)))

df_NA %>% group_by(Tumor_Sample_Barcode_post) %>% mutate(Tumor_Sample_Barcode_pre = case_when(Tumor_Sample_Barcode_pre == NA ~ Tumor_Sample_Barcode_pre))

数据结构

df_NA <- structure(list(Tumor_Sample_Barcode_post = c("s_C_VWPHV0_P002_d", 
"s_C_3438KR_P002_d", "s_C_3438KR_P002_d", "s_C_V2MVLR_P002_d", 
"s_C_JXLC4H_P002_d", "s_C_UXUR8D_P002_d", "s_C_XUCF8U_P002_d", 
"s_C_JXLC4H_P002_d", "s_C_XUCF8U_P002_d", "s_C_V2MVLR_P002_d", 
"s_C_VWPHV0_P002_d", "s_C_UXUR8D_P002_d"), Tumor_Sample_Barcode_pre = c(NA, 
NA, "s_C_3438KR_P001_d", NA, "s_C_JXLC4H_P001_d", NA, NA, NA, 
"s_C_XUCF8U_P001_d", "s_C_V2MVLR_P001_d", "s_C_VWPHV0_P001_d", 
"s_C_UXUR8D_P001_d")), class = c("grouped_df", "tbl_df", "tbl", 
"data.frame"), row.names = c(NA, -12L), groups = structure(list(
    Tumor_Sample_Barcode_post = c("s_C_3438KR_P002_d", "s_C_JXLC4H_P002_d", 
    "s_C_UXUR8D_P002_d", "s_C_V2MVLR_P002_d", "s_C_VWPHV0_P002_d", 
    "s_C_XUCF8U_P002_d"), .rows = structure(list(2:3, c(5L, 8L
    ), c(6L, 12L), c(4L, 10L), c(1L, 11L), c(7L, 9L)), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), row.names = c(NA, -6L), .drop = TRUE, class = c("tbl_df", 
"tbl", "data.frame")))

解决方案

代码问题分析

  • 第一段代码中replace_na的第二个参数错误:!is.na(Tumor_Sample_Barcode_pre)返回布尔值,而非需要填充的非NA标签值。
  • 第二段代码中case_when判断NA的方式错误:不能用== NA,需用is.na(),且未实现填充逻辑。

正确实现方式

提供两种可靠的填充方法:

方法1:使用fill函数(推荐)

利用dplyr::fill函数,分组后同时向上/向下填充缺失值,确保同组所有NA被非NA值覆盖:

library(dplyr)

df_filled <- df_NA %>%
  group_by(Tumor_Sample_Barcode_post) %>%
  fill(Tumor_Sample_Barcode_pre, .direction = "updown") %>%
  ungroup()
方法2:提取同组非NA值替换缺失值

先提取每组的非NA值(同组非NA值唯一),再替换对应NA:

library(dplyr)

df_filled <- df_NA %>%
  group_by(Tumor_Sample_Barcode_post) %>%
  mutate(Tumor_Sample_Barcode_pre = ifelse(
    is.na(Tumor_Sample_Barcode_pre),
    first(na.omit(Tumor_Sample_Barcode_pre)),
    Tumor_Sample_Barcode_pre
  )) %>%
  ungroup()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 21:10:30