Incomplete list in dataframe

Here is a short list:

foo <- list(c("johnny", "joey"), character(0), "deedee") [[1]] [1] "johnny" "joey" [[2]] character(0) [[3]] [1] "deedee" 

How can I convert it to this data frame?

  list_item name 1 1 johnny 2 1 joey 3 3 deedee 

All the data list solutions that I have seen do not work, because my list is not complete.

+6
source share
5 answers

We can use stack from base R after setting names for "foo" as a sequence of "foo".

 stack(setNames(foo, seq_along(foo))) # values ind #1 johnny 1 #2 joey 1 #3 deedee 3 
+3
source

The melt function of reshape2 also works on lists. So you can use:

 library(reshape2) melt(foo) # value L1 #1 johnny 1 #2 joey 1 #3 deedee 3 

I believe that you know how to change names later.

+7
source

Here is one way with base R:

 data.frame(list_item=rep(seq_along(foo), sapply(foo, length)), name=unlist(foo)) ## list_item name ## 1 1 johnny ## 2 1 joey ## 3 3 deedee 

As mentioned in the comments of @RichardScriven, sapply(foo, length) can be replaced with lengths(foo) .

+5
source

melt is ultra-cool (system time 1.74 for a 10k list) and the @jbaums' unlist is just as fast when lengths (1.72) is used, but the @akrun stack solution cause it to be so ridiculously fast (0.06). As expected, the cycle is the slowest (21.86).

+1
source

This works with this example:

 foo <- list(c("johnny", "joey"), character(0), "deedee") result=data.frame() for(listitem.no in 1:length(foo)){ for(vectoritem in foo[[listitem.no]]) result <- rbind(result, c(listitem.no, as.character(vectoritem)), stringsAsFactors=FALSE) } 

NTN, Bernhard

0
source

All Articles