我想在一个数据帧列中计算NA值的数量。假设我的数据帧称为df,我正在考虑的列的名称是col。我提出的方法如下:

sapply(df$col, function(x) sum(length(which(is.na(x)))))  

这是一个好的/最有效的方法吗?


当前回答

另一个选项使用complete。这样的案例:

df <- data.frame(col = c(1,2,NA))
df
#>   col
#> 1   1
#> 2   2
#> 3  NA
sum(!complete.cases(df$col))
#> [1] 1

于2022-08-27使用reprex v2.0.2创建

其他回答

你想太多了:

sum(is.na(df$col))

类似于hute37的答案,但使用了purrr包。我认为这种tidyverse方法比AbiK提出的答案更简单。

library(purrr)
map_dbl(df, ~sum(is.na(.)))

注意:波浪号(~)创建一个匿名函数。还有'。’指的是匿名函数的输入,在本例中为data.frame df。

一种统计数据帧中每一列空值的方法:

library(tidyverse)
library(purrr)

df %>%
    map_df(function(x) sum(is.na(x))) %>%
    gather(feature, num_nulls) %>%
    print(n = 100)

获得所有列NA计数的一个快速简单的Tidyverse解决方案是使用summarise_all(),我认为这比使用purrr或sapply更容易读取解决方案

library(tidyverse)
# Example data
df <- tibble(col1 = c(1, 2, 3, NA), 
             col2 = c(NA, NA, "a", "b"))

df %>% summarise_all(~ sum(is.na(.)))
#> # A tibble: 1 x 2
#>    col1  col2
#>   <int> <int>
#> 1     1     2

或者使用更现代的across()函数:

df %>% summarise(across(everything(), ~ sum(is.na(.))))
sapply(name of the data, function(x) sum(is.na(x)))