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

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

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


当前回答

你想太多了:

sum(is.na(df$col))

其他回答

如果你在一个数据帧中寻找每一列的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

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

library(tidyverse)
library(purrr)

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

试试这个:

length(df$col[is.na(df$col)])

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

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