6

Here's a little list:

foo <- list(c("johnny", "joey"), character(0), "deedee")

[[1]]
[1] "johnny" "joey"  

[[2]]
character(0)

[[3]]
[1] "deedee"

How can I transform it into this data frame?

  list_item   name
1         1 johnny
2         1   joey
3         3 deedee

All list-to-dataframe solutions I've seen don't work because my list in incomplete.

5 Answers 5

7

The melt function of package reshape2 works on lists, too. So you can use:

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

I believe you know how to change the names afterwards.

5

Here's 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 by @RichardScriven in comments, sapply(foo, length) can be replaced with lengths(foo).

0
3

We can use stack from base R after setting the names of the 'foo' as the sequence of 'foo'.

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

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

0

This works with the given 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)
}

HTH, Bernhard

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.