Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incomplete list into dataframe

Tags:

list

dataframe

r

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.

like image 705
hyco Avatar asked Jul 13 '16 08:07

hyco


3 Answers

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.

like image 196
talat Avatar answered Oct 02 '22 01:10

talat


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).

like image 21
jbaums Avatar answered Oct 02 '22 02:10

jbaums


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
like image 31
akrun Avatar answered Oct 02 '22 01:10

akrun