我想在一个数据帧列中计算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创建

其他回答

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

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

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

我从本地目录读取csv文件。以下代码适用于我。

# to get number of which contains na
sum(is.na(df[, c(columnName)]) # to get number of na row

# to get number of which not contains na
sum(!is.na(df[, c(columnName)]) 

#here columnName is your desire column name

你想太多了:

sum(is.na(df$col))

用户rrs的答案是正确的,但它只告诉你在数据帧的特定列中NA值的数量,你正在传递来获得整个数据帧的NA值的数量,试试这个:

apply(<name of dataFrame>, 2<for getting column stats>, function(x) {sum(is.na(x))})

这就行了

获得所有列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(.))))