3

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?

3
  • 2
    What exactly is a NULL value in your data? You sure you're not looking for NA? Commented Jun 30, 2013 at 8:45
  • Yes, I realize it would make equal sense to replace NULL with NA. 'NULL' values are those that are present in a SQL table entry. Commented Jun 30, 2013 at 16:27
  • @Enigman, probably you should accept the answer (since it's working) and mark this closed. Commented Jul 5, 2013 at 5:38

3 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

@Enigman, right--it appears not. If you view the str of the object created with this answer, both a and b are lists.
Not gonna lie, data.frame of lists (list of lists) is super interesting data structure. If you do it with a named list of lists that are themselves named, you will be able to do df$column$row. And then assign whatever to this.
2
 as.data.frame(do.call(rbind, z))
     a b
1    1 2
2    2 3
3 NULL 4

Comments

2

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

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.