3

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!

3
  • You can place it in a list i.e. list(a, b, c, d, e, f) or create a list column in data.frame ie. data.frame(a, b, c, d= I(list(d)), e) Commented Jul 11, 2017 at 1:14
  • 6
    Use NA instead. Commented Jul 11, 2017 at 1:16
  • As alistaire said, use NA instead. The reasoning is that assigning NULL to a variable or data frame column tells R to remove that variable or column from your workspace. It is not the same value as null in other languages. Commented Jul 11, 2017 at 1:24

1 Answer 1

3

Try this:

L <- list(a = a, b = b, c = c, d = d, e = e, f = f)
DF <- as.data.frame(matrix(L, 1, dimnames = list(NULL, names(L))))
DF
##   a b c    d    e f
## 1 1 2 3 NULL text  

str(DF)
## 'data.frame':   1 obs. of  6 variables:
##  $ a:List of 1
##   ..$ a: num 1
##  $ b:List of 1
##   ..$ b: num 2
##  $ c:List of 1
##   ..$ c: num 3
##  $ d:List of 1
##   ..$ d: NULL
##  $ e:List of 1
##   ..$ e: chr "text"
##  $ f:List of 1
##   ..$ f: chr 

Also note that the matrix m looks like this:

str(m)
## List of 6
##  $ : num 1
##  $ : num 2
##  $ : num 3
##  $ : NULL
##  $ : chr "text"
##  $ : chr(0) 
##  - attr(*, "dim")= int [1:2] 1 6
##  - attr(*, "dimnames")=List of 2
##   ..$ : NULL
##   ..$ : chr [1:6] "a" "b" "c" "d" ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.