r语言 - 如何确定给出误差的数据点



我在R中有一个代码,每次读取一行,通过data.frame,如果满足特定的一组条件,则更改data.frame中一个变量的值。在伪代码中:

for(i in 1:nrow(data)) {
 if (conditions on data[i,]) { change value } else {do nothing}
}

当代码运行时,在某个点停止并抛出以下错误消息:Error in if (condition : missing value where TRUE/FALSE needed

我理解错误信息意味着,在某一点上,当评估if语句中的条件时,结果是Na而不是TRUEFALSE

然而,当我通过使用"存储"在R中的i的值(并且我假设是抛出错误的数据集的行)来尝试R中的条件时,我得到TRUE的答案。我是否正确理解i的值允许我识别数据帧的哪一行抛出错误?如果不是,我是否应该寻找其他方法来识别数据集的哪一行导致错误?

我想答案是"是"

 print(i) ## Error: doesn't exist yet
 for (i in 1:10) {
     if (i==4) stop("simulated error")
 }
 print(i)  ## 4

try()函数也很有用。在这里,我们创建一个函数f来模拟错误,然后使用try(),这样我们就可以运行整个循环。当遇到错误时,我们不会停止,而是填充一个表示错误代码的值(在本例中为10000)。(我们也可以将错误行为设置为无操作,即直接进行循环的下一次迭代;在这种情况下,NA将留在错误位置。)

 f <- function(x) {
     if (x==4) stop("simulated error")
     return(x)
 }
 results <- rep(NA,10)
 for (i in 1:10) {
     res <- try(f(i))
     if (is(res,"try-error")) {
        results[i] <- 10000
     } else {
        results[i] <- res
    }
 }

只要你的for循环不在函数内部,i将等于它在错误之前遇到的最终值。因此在你的错误之后:

 data[i, ]

应该给你病理行

如果你在一个函数中运行,根据作用域规则,i应该随函数而死。在这种情况下,我会修改你的代码,打印出每一行(或I),直到它结束:

 for(i in 1:nrow(data)) {
   print(i) #or print(data[i, ])
   if (conditions on data[i,]) { change value } else {do nothing}
}

1)替换值

replace不是更好吗?

这里有一些例子:

在你的情况下

 replace (df$column, your_condition, value)
2)过滤

如果你确定你的数据只包含true/false或NAs,你可以:

a)在特定列

中具有NAs的子集行
df[(is.na(df$column)), ]

b)从dplyr

中过滤出使用filter的内容
library("dplyr")
filter(df, is.na(column)) # filter NAs in dplyr you don't have to use $ to specify column
filter(df, !is.na(column) & column!="FALSE") # filter everything other than NA and FALSE
filter(df, column!="TRUE" & column!="FALSE") # careful with that, won't return NAs

3)选择行号

最后,当您需要NAs所在的特定行号时,使用which

which(is.na(df$column)) # row numbers with NAs
which(df$column!="TRUE") # row numbers other than TRUEs
which(df$column!="TRUE" & df$column!="FALSE") # again, won't return NAs

最新更新