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

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

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


当前回答

我从本地目录读取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

其他回答

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

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

这就行了

如果你在一个数据帧中寻找每一列的NA计数,那么:

na_count <-sapply(x, function(y) sum(length(which(is.na(y)))))

应该会给你一个包含每列计数的列表。

na_count <- data.frame(na_count)

应该像这样在数据框架中输出数据:

----------------------
| row.names | na_count
------------------------
| column_1  | count

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

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

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

sapply(name of the data, function(x) sum(is.na(x)))

为了保证完整性,你也可以在table中使用useNA参数。例如table(df$col, useNA="always")将统计所有非NA的情况和NA的情况。