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

R语言如何提取含NA缺失值行的Class值及对应缺失列名

提取数据集缺失值关联Class信息的实现方案

核心目标

  • 提取数据集第一列Class的分类值
  • 定位所有NA缺失值对应的行号、所属Class类别、缺失值所在列名
  • 基于提取结果验证存在缺失值的预测变量是否与其所属Class类别相关

现有方案局限

  • visdat::vis_miss(Soybean)仅能展示缺失数据整体分布概览,无法关联输出Class名称与对应存在缺失的预测变量
  • 常规列值匹配方案需要预先明确所有目标值,无法自动遍历全量缺失值适配需求

测试样例数据

library(mlbench)
data(Soybean)
Soybean <-  Soybean %>% as.data.frame(row.names = 1:nrow(.))
Soybean[c(32:39),]

运行后输出的样例数据片段:

Class date plant.stand precip temp hail crop.hist area.dam sever seed.tmt germ
32 phytophthora-rot    1           1      2    1 <NA>         3        1  <NA>     <NA> <NA>
33 phytophthora-rot    2           1      2    2 <NA>         2        1  <NA>     <NA> <NA>
34 phytophthora-rot    1           1      2    0    0         2        1     2        1    1
35 phytophthora-rot    2           1      2    2 <NA>         2        1  <NA>     <NA> <NA>
36 phytophthora-rot    3           1      2    1 <NA>         2        1  <NA>     <NA> <NA>
37 phytophthora-rot    0           1      1    1    0         1        1     1        0    0
38 phytophthora-rot    3           1      2    0    0         2        1     2        1    1
39 phytophthora-rot    2           1      1    1 <NA>         0        1  <NA>     <NA> <NA>

期望输出格式

32 phytophthora-rot  hail 
32 phytophthora-rot  sever
32 phytophthora-rot  seed.tmt 
32 phytophthora-rot  germ
33 phytophthora-rot  hail
33 phytophthora-rot  sever
33 phytophthora-rot  seed.tmt 
33 phytophthora-rot  germ
39 phytophthora-rot  hail
39 phytophthora-rot  sever

可运行实现代码

library(tidyverse)
library(mlbench)
data(Soybean)
Soybean <- Soybean %>% as.data.frame(row.names = 1:nrow(.))

# 提取所有缺失值的关联信息
na_record <- which(is.na(Soybean |> select(-Class)), arr.ind = TRUE) |>
  as.data.frame() |>
  mutate(
    row_id = row,
    class = Soybean$Class[row],
    miss_column = colnames(Soybean |> select(-Class))[col]
  ) |>
  select(row_id, class, miss_column) |>
  arrange(row_id, miss_column)

# 打印结果,格式与期望完全匹配
print(na_record, row.names = FALSE)

基于输出的na_record结果,可直接通过列联表检验、卡方检验等方式,验证各预测变量的缺失情况和Class分类的相关性,示例检验代码:

# 检验hail变量的缺失是否和Class存在显著关联
chisq.test(table(Soybean$Class, is.na(Soybean$hail)))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 01:01:14