Skip to content
Prev 299668 / 398503 Next

fill 0-row data.frame with 1 line of NAs

On 7/10/2012 7:53 AM, Peter Ehlers wrote:
Using NA subscripting seems even better

empty <- function(x) {
   if(NROW(x) == 0) {
     x[NA,]
   } else {
     x
   }
}

It even preserves the factor nature of things:

 > empty(iris[iris$Specis=='zz',])
    Sepal.Length Sepal.Width Petal.Length Petal.Width Species
NA           NA          NA           NA          NA    <NA>
 > str(empty(iris[iris$Specis=='zz',]))
'data.frame':   1 obs. of  5 variables:
  $ Sepal.Length: num NA
  $ Sepal.Width : num NA
  $ Petal.Length: num NA
  $ Petal.Width : num NA
  $ Species     : Factor w/ 3 levels "setosa","versicolor",..: NA