Create dataframe from objects with some NULL values in R

Viewed 1272

I have n objects that I want to combine together as a 1-row by n-column data frame. However, some of the objects may be NULL or empty strings and I would like the names of the objects to become the names of the dataframe.

So if I have

a <- 1
b <- 2
c <- 3
d <- NULL
e <- 'text'
f <- character(0)

I would like to do something like:

mydf <- data.frame(a, b, c, d, e)

and have the NULL values dropped when creating the data frame:

> mydf
  a b c    e
1 1 2 3 text

However, if I try it with the NULL objects and empty strings I get the following error:

Error in data.frame(a, b, c, d, e) : 
  arguments imply differing number of rows: 1, 0

And if I write some sort of function to filter out NULL objects, I lose the names of my objects and get bizarre column names.

Thanks for the help!

1 Answers
Related