简体   繁体   中英

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

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.

您可以将apply与匿名函数一起使用,如下所示:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM