Enigman
Enigman

Reputation: 640

Convert list with NULL entres to data.frame in R

I have a list named z :

z<-list( list(a=1, b=2),  list(a=2, b=3), list(a=NULL, b=4))

I want this to be converted to a data.frame with the corresponding a entry in the data.frame assigned as NULL. Doing this,

do.call( rbind, lapply( z, data.frame, stringsAsFactors=TRUE ) )

as expected, gives this error:

 Error in data.frame(a = NULL, b = 4, check.names = FALSE, stringsAsFactors = TRUE) : 
 arguments imply differing number of rows: 0, 1

What is the work around?

Upvotes: 3

Views: 2472

Answers (3)

Ricky
Ricky

Reputation: 4686

If you're interested in data frame of numeric values instead of data frame of lists, you can try the below.

lz <- lapply(z, function(x) {
    nonnull <- sapply(x, typeof)!="NULL"
    do.call(data.frame, c(x[nonnull], stringsAsFactors=FALSE))
})

require(plyr)
df <- ldply(lz)

Note that the result will have NULLs converted to NAs to form valid dataframes.

> df
   a b
1  1 2
2  2 3
3 NA 4
> str(df)
'data.frame':   3 obs. of  2 variables:
 $ a: num  1 2 NA
 $ b: num  2 3 4

Upvotes: 2

user1609452
user1609452

Reputation: 4444

 as.data.frame(do.call(rbind, z))
     a b
1    1 2
2    2 3
3 NULL 4

Upvotes: 2

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

Is this what you are trying to do?

> data.frame(do.call(rbind, z))
     a b
1    1 2
2    2 3
3 NULL 4

Upvotes: 5

Related Questions