循环错误:is.na() 应用于 'NULL' 类型的非(列表或向量)
Error in loop: is.na() applied to non-(list or vector) of type 'NULL'
我尝试像这样计算数据框中每一列的 NA
a = c('a', 'b', NA)
b = c('a', NA, NA)
c = c(NA, NA, NA)
data = data.frame(cbind(a, b, c))
这个有效
sum(is.na(data$a))
但是当我尝试使用 LOOP
for(i in data[, 1:3]) {
k=sum(is.na(data$i))
cat(k, '\n')
}
我得到
Warning messages:
1: In is.na(data$i) :
is.na() applied to non-(list or vector) of type 'NULL'
如何解决?谢谢
如何使用循环来索引数据框(而不是数据框本身)
# 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')
}
您可能还想探索应用函数,而不是遍历列。
您可以像这样将 apply 与匿名函数一起使用:
apply(data, 2, function(x) sum(is.na(x)) )
我尝试像这样计算数据框中每一列的 NA
a = c('a', 'b', NA)
b = c('a', NA, NA)
c = c(NA, NA, NA)
data = data.frame(cbind(a, b, c))
这个有效
sum(is.na(data$a))
但是当我尝试使用 LOOP
for(i in data[, 1:3]) {
k=sum(is.na(data$i))
cat(k, '\n')
}
我得到
Warning messages:
1: In is.na(data$i) :
is.na() applied to non-(list or vector) of type 'NULL'
如何解决?谢谢
如何使用循环来索引数据框(而不是数据框本身)
# 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')
}
您可能还想探索应用函数,而不是遍历列。
您可以像这样将 apply 与匿名函数一起使用:
apply(data, 2, function(x) sum(is.na(x)) )