Edward
Edward

Reputation: 4623

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

I try to count NA for every column in dataframe 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 try use LOOP

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

  k=sum(is.na(data$i)) 
  cat(k, '\n')
}

i get

Warning messages:
1: In is.na(data$i) :
  is.na() applied to non-(list or vector) of type 'NULL'

How to fix it? thanx

Upvotes: 0

Views: 749

Answers (2)

KoenV
KoenV

Reputation: 4283

You could use apply with an anonymous function like this:

apply(data, 2,  function(x) sum(is.na(x)) )

Upvotes: 1

din
din

Reputation: 692

How about using the loop to index the data frame (not the data frame itself)

# 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')
}

You might want to explore apply functions as well, rather than looping through columns.

Upvotes: 1

Related Questions