R 为什么na.omit会将一行添加到空数据帧?

R 为什么na.omit会将一行添加到空数据帧?,r,dataframe,R,Dataframe,我有一个代码,做了一些类似的事情 d <- load a data.frame, possible an empty one... d <- na.omit(d) if (NROW(d)>0) { do something... } 为什么na.omit对我这样做?问题不在于(必然)na.omit,而在于索引一个没有行的数据.frame。例如: > DF <- data.frame() > DF[TRUE, ] data frame with 0 colu

我有一个代码,做了一些类似的事情

d <- load a data.frame, possible an empty one...
d <- na.omit(d)
if (NROW(d)>0) {
 do something...
}
为什么na.omit对我这样做?

问题不在于(必然)na.omit,而在于索引一个没有行的
数据.frame
。例如:

> DF <- data.frame()
> DF[TRUE, ]
data frame with 0 columns and 1 rows
> DF[1, ]
data frame with 0 columns and 1 rows
> DF
data frame with 0 columns and 0 rows

更好的解决方法是使用@Arun的建议

这是因为
na.ommit
有一个逻辑向量
ommit
(在其代码中),该向量对于要保留的行设置为
FALSE
,对于要删除的行设置为
TRUE

但是,在检查输入数据之前,
ommit
最初设置为FALSE。请查看要删除哪些行并更新
ommit
的值。由于您的输入是空的data.frame,因此没有更新的值,
omit
保留先前的设置FALSE。然后,
na.omit
调用:

object[!omit, , drop=FALSE]
在你的情况下,这是:

data.frame()[TRUE, , drop=FALSE]
其中:

# data frame with 0 columns and 1 rows

下面是
na.omit.data.frame
(可以通过执行
getS3method(“na.omit”、“data.frame”)
获得)的代码。未为空data.frame运行的部分将被注释掉

n <- length(object)
omit <- FALSE
vars <- seq_len(n) # equals integer(0) in your case
for (j in vars) { # the loop is not run at all
#     x <- object[[j]]
#     if (!is.atomic(x)) 
#         next
#     x <- is.na(x)
#     d <- dim(x)
#     if (is.null(d) || length(d) != 2L) 
#         omit <- omit | x
#     else for (ii in 1L:d[2L]) omit <- omit | x[, ii]
# }
xx <- object[!omit, , drop = FALSE]
# if (any(omit > 0L)) { # this is also not run
#     temp <- setNames(seq(omit)[omit], attr(object, "row.names")[omit])
#     attr(temp, "class") <- "omit"
#     attr(xx, "na.action") <- temp
# }
xx

你能提供一些示例数据以使问题重现吗?@flowla基本上问题是
data.frame()
na.omit(data.frame())
有不同的行数。这(
nrow(na.omit(data.frame()))>nrow(data.frame())
听起来像是一个应该向邮件列表报告的bug,或者说是一个bug。报告第一个解决方法将产生一个向量,并且该行的所有其他条目都将使用NA。@Arun,这将是一个向量,是的,但它将具有正确的值。尝试,例如,
DF I stand corrected,我期待一个不同的out从na输出。忽略此选项即可。
完成。cases
返回0行数据帧。请检查我的答案。
# data frame with 0 columns and 1 rows
n <- length(object)
omit <- FALSE
vars <- seq_len(n) # equals integer(0) in your case
for (j in vars) { # the loop is not run at all
#     x <- object[[j]]
#     if (!is.atomic(x)) 
#         next
#     x <- is.na(x)
#     d <- dim(x)
#     if (is.null(d) || length(d) != 2L) 
#         omit <- omit | x
#     else for (ii in 1L:d[2L]) omit <- omit | x[, ii]
# }
xx <- object[!omit, , drop = FALSE]
# if (any(omit > 0L)) { # this is also not run
#     temp <- setNames(seq(omit)[omit], attr(object, "row.names")[omit])
#     attr(temp, "class") <- "omit"
#     attr(xx, "na.action") <- temp
# }
xx
DF <- data.frame()
DF[complete.cases(DF), ]
# data frame with 0 columns and 0 rows

DF <- data.frame(x=1:2, y=c(2,NA))
DF[complete.cases(DF), ]
#   x y
# 1 1 2