Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am trying to count NA values from every column in data frame like this

a = c('a', 'b', NA)

b = c('a', NA, NA)

c = c(NA, NA, NA)

data = data.frame(cbind(a, b, c))

This works

sum(is.na(data$a))

But when i tried using LOOP

for(i in data[, 1:3]) {

  k=sum(is.na(data$i)) 

  cat(k, '\n')

}

I am getting

Warning messages:

1: In is.na(data$i) :

  is.na() applied to non-(list or vector) of type 'NULL'

How do I fix it?

1 Answer

0 votes
by (36.8k points)

Use the loop to index the data frame

# use 1:3 as index for the columns

for(i in 1:3) {

  # instead of data$i; use data[ , i] to 

  # select all rows and the ith colum

  k=sum(is.na(data[ , i])) 

  cat(k, '\n')

}

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...