打印r中数据框中NA值的行



我想让函数检查count = NA的值然后它会打印出"Not validate "否则会显示"成功">

order = data.frame(item = c("A","B","C"), count = c(1,2,NA))
check <- function(order){
if (order$count[is.na(order$count),] ){
print(paste(order$item,"not value"))
}
else {
print("success")
}
}

但是它产生了错误

我认为你可以这样缩短整个函数:

# define function:
check <- function(x) { 
ifelse(is.na(x), "not value", "success")
}
# input function:
check(order$count)
[1] "success"   "success"   "not value"

你可以试试这个方法

check <- function(order){
if (any(is.na(order$count)) ){
print(paste(order$item[is.na(order$count)],"not value"))
}
else {
print("success")
}
}
check(order)
[1] "C not value"

错误Error in order$count[is.na(order$count), ] : incorrect number of dimensions的原因是order$count是矢量,但你调用[is.na(order$count), ]

同时,order$count[is.na(order$count)]NA,不适合作为if语句的条件输入。

如果您想按行检查items,您可以尝试

check <- function(order){
for (i in 1:nrow(order)){
if (is.na(order$count[i])) {
print(paste(order$item[i], "not value"))
} else {
print(paste(order$item[i], "success"))
}
}
}
check(order)  
[1] "A success"
[1] "B success"
[1] "C not value"

还有另一种方法:

library(car)
recode(is.na(order$count), "FALSE='success'; TRUE='not valid'")
[1] "success"   "success"   "not valid"

相关内容

  • 没有找到相关文章

最新更新