I have a list of this format:
region_list
region_parent_1 character[1]
region_parent_2 character[3]
region_parent_3 character[1]
region_parent_4 character[0]
....
where each region_parent is a character vector of vary length contain various regions.
And I want to create a tibble that looks like this
region_parent, region
region_parent_1, region_a
region_parent_2, region_b
region_parent_2, region_c
region_parent_2, region_d
region_parent_3, region_e
region_parent_4, region_parent_4
....
Notice that when the character vector is empty I want region_parent that is the name of that character vector in the list to sub in for the missing region element.
I have mostly figured out coerce the list into the tibble I want by using the following:
lambda = function(array, region_parent) {
df = array %>%
as.data.frame() %>%
setNames("region") %>%
mutate(region_parent = region_parent)
return(df)
}
region_list = map2(region_list, names(region_list), lambda)
region_list = rbindlist(region_list, use.names = TRUE)
However it drops any element in the list where the character vector has zero regions/elements in it.
I was close to a fix by modifying the lambda function like this but it turns the tibble into an array again and fails to correctly set names and add the region_parent column.
lambda = function(array, region_parent) {
df = array %>%
as.data.frame() %>%
{if (nrow(.) == 0) rbind(region_parent) else .} %>%
setNames("region") %>%
mutate(region_parent = region_parent)
return(df)
}
Any ideas how to prevent these empty vectors from being dropped or a simpler way to collapse this list into a tibble would be welcome.