r - Why na.omit adds a row to empty dataframe? -
i have code doing like
d <- load data.frame, possible empty one... d <- na.omit(d) if (nrow(d)>0) { something... } this appears wrong due fact applying na.omit empty data frame adds row it:
data.frame() data frame 0 columns , 0 rows na.omit(data.frame()) data frame 0 columns , 1 rows why na.omit doing me?
this because na.omit has logical vector omit (in code) gets set false rows keep , true rows remove.
however, omit set false before checking on input data.frame rows remove , update value of omit. since input empty data.frame, there no values updated , omit retains earlier set false. , then, na.omit calls:
object[!omit, , drop=false] which in case is:
data.frame()[true, , drop=false] which gives:
# data frame 0 columns , 1 rows here's code na.omit.data.frame (which can obtained doing gets3method("na.omit", "data.frame")). part not run empty data.frame commented out.
n <- length(object) omit <- false vars <- seq_len(n) # equals integer(0) in case (j in vars) { # loop not run @ # 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 (ii in 1l:d[2l]) omit <- omit | x[, ii] # } xx <- object[!omit, , drop = false] # if (any(omit > 0l)) { # not run # temp <- setnames(seq(omit)[omit], attr(object, "row.names")[omit]) # attr(temp, "class") <- "omit" # attr(xx, "na.action") <- temp # } xx solution:
you use complete.cases instead.
df <- data.frame() df[complete.cases(df), ] # data frame 0 columns , 0 rows df <- data.frame(x=1:2, y=c(2,na)) df[complete.cases(df), ] # x y # 1 1 2
Comments
Post a Comment