Reputation: 905
I would like to convert the following list into a dataframe.
test <- list(list("a",c("b","c","d"),character(0)),list("j",c("r","s"),character(0)),list("h",character(0),"i"))
I tried the following:
df.test <- do.call(rbind,Map(data.frame, V1=sapply(test, "[[", 1),V2=sapply(test, "[[", 2),V3=sapply(test, "[[", 3)))
But this doesn't work with nested lists containing character(0). A satisfactory output looks something like this:
V1 V2 V3
1 a b NA
2 a c NA
3 a d NA
4 j r NA
5 j s NA
6 h NA i
Many thanks in advance.
Upvotes: 1
Views: 452
Reputation: 28695
library(tidyverse)
test %>%
map_df(~.x %>%
map(~if(length(.)) . else NA) %>%
do.call(what = cbind) %>%
as_tibble)
Gives
V1 V2 V3
<chr> <chr> <chr>
1 a b NA
2 a c NA
3 a d NA
4 j r NA
5 j s NA
6 h NA i
Upvotes: 3