【问题标题】:Calculate the percentage of missing values per column using R [duplicate]使用R计算每列缺失值的百分比[重复]
【发布时间】:2018-09-08 23:41:34
【问题描述】:

我正在使用一个包含大约 1000 列(变量)和 64000 行的数据框。我需要知道每一列的缺失值百分比以及整个数据框缺失值的总百分比。

有谁知道使用 R 更有效的方法吗?

非常感谢!

【问题讨论】:

  • 欢迎堆栈溢出!阅读本文将为您提供更有成效的答案,尽管上面的评论使您顺利进行。 stackoverflow.com/help/how-to-ask
  • 您可能需要检查 VIM 包以可视化和检查丢失的数据。
  • 非常感谢,phiver!

标签: r


【解决方案1】:

一种方法是使用tidyr::gather 将您的数据框转换为长格式,然后在分组后对每一列应用类似的计算。

假设一个数据框(为了说明目的比你的小):

library(tidyverse)
df <- tibble(
column = rep(paste0("col_", str_pad(1:1000, 4, pad = "0")), each = 640),
value = sample(c(0:100, NA_integer_), replace = TRUE, 6.4E5),
line = rep(1:640, 1E3)
) %>% spread(column, value)

先用 tidyr::gather 转换成 long,然后用 group_by,然后按列汇总得到平均缺失值:

df %>%
gather(col, value, -line) %>%
group_by(col) %>%
summarize(missing_share = mean(is.na(value)))

    # A tibble: 1,000 x 2
   col      missing_share
   <chr>            <dbl>
 1 col_0001       0.0109 
 2 col_0002       0.0141 
 3 col_0003       0.0125 
 4 col_0004       0.00938
 5 col_0005       0.0141 
 6 col_0006       0.00625
 7 col_0007       0.00312
 8 col_0008       0.00781
 9 col_0009       0.00781
10 col_0010       0.00781
# ... with 990 more rows

或跳过分组步骤以获得整体缺失:

df_NA_overall <- df %>%
gather(col, value, -line) %>%
summarize(missing_share = mean(is.na(value)))

# A tibble: 1 x 1
  missing_share
          <dbl>
1       0.00989

使用purrr::map 可以更快地完成第一部分:

map(df, ~mean(is.na(.))) 

$line
[1] 0

$col_0001
[1] 0.0109375

$col_0002
[1] 0.0140625

$col_0003
[1] 0.0125

$col_0004
[1] 0.009375

$col_0005
[1] 0.0140625

$col_0006
[1] 0.00625

$col_0007
[1] 0.003125

$col_0008
[1] 0.0078125

$col_0009
[1] 0.0078125

【讨论】:

  • 嗨,乔恩!非常感谢您的出色解决方案。它按我预期的方式工作。
猜你喜欢
  • 2022-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多