Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (5.3k points)

I want to count the number of NA values in a data frame column. Say my data frame is called df, and the name of the column I am considering is col. The way I have come up with is the following:

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

Is this a good/most efficient way to do this?

1 Answer

0 votes
by

To count the number of NA values in a column, you can use the sum() function as follows:

sum(is.na(df$col))

For example:

In the following data frame:

df <- data.frame(A = sample(c(1:20), 10),

                 B = sample(c(TRUE, FALSE,NA), 10, rep = TRUE))

df

    A     B

1   7    NA

2  12 FALSE

3   9  TRUE

4  11 FALSE

5  20    NA

6  17 FALSE

7   3    NA

8  10 FALSE

9  13    NA

10 18    NA

To count the number of NA values in column ‘B’:

 sum(is.na(df$B))

[1] 5

Related questions

0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...