0

I have a row-NA-removal functional called foo. It works great ONLY for data.frame with at least 2 columns.

BUT for data.frames with only 1 column, it basically changes the inputted data.frame object to an "integer" object.

I wonder how to fix the function so it preserves the class of the inputted data.frame in its output both for multi-column and single-column data.frame inputs?

X <- data.frame(a = c(1, NA, 2, 3), b = c(1, NA, 4, 5)) # data.frame

foo <- function(X){                                     # Function `foo`

 X[rowSums(is.na(X) | X == "") != ncol(X), ]
}

foo(X[c("a", "b")])    # Outputs a data.farme with NAs removed (as expected)

foo(X["a"])     #   outputs: `> 1 2 3`  basically a simple integer vector !!!

# My EXPECTED OUTPUT for  `foo(X["a"])` is a data.frame like:

    #   a
    #1  1
    #2  2
    #3  3  

1 Answers1

3

You can use argument drop for operator bracket

foo <- function(X){ # Function `foo` 
    X[rowSums(is.na(X) | X == "") != ncol(X), ,drop =FALSE] 
} 

Argument drop makes the result to keep its initial class.

Manos Papadakis
  • 564
  • 5
  • 17