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!
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" ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With