I have a list with multiple levels that I would like to the data level into a data frame, where the variable chr is collapsed into single strings.
myList <- list(total_reach = list(4),
data = list(list(reach = 2,
chr = list("A", "B", "C"),
nr = 3,
company = "Company A"),
list(reach = 2,
chr = list("A", "B", "C"),
nr = 3,
company = "Company B")))
I would like to transform this into a data frame that looks like this:
reach chr nr company
1 2 A, B, C 3 Company A
2 2 A, B, C 3 Company B
Using dplyr and data.table I've come this far.
library(data.table)
library(dplyr)
df <- data.frame(rbindlist(myList[2])) %>% t() %>% as.data.frame()
colnames(df) <- names(myList$data[[1]])
rownames(df) <- c(1:nrow(df))
df$chr <- as.character(df$chr)
df <- df %>%
mutate_all(funs(unlist(.recursive = F, use.names = F)))
However, chr column contains strings with "list()" wrapped around it.
reach chr nr company
1 2 list("A", "B", "C") 3 Company A
2 2 list("A", "B", "C") 3 Company B
A) Is there a better way to unlist this kind of list and turn it into a data frame?
B) How do I collapse the lists in chr to strings or factors?