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.
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.
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)
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With