Handling NAs when Converting List to Tibble

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.

library(tidyverse)
(d1<- list(
  region_parent_1= "a",
  region_parent_2= letters[1:3],
  region_parent_3=character(0)
))

enframe(d1) |> 
  unnest_longer(col=value,keep_empty = TRUE) |>
  mutate(value=if_else(is.na(value),name,value))

This was a simpler way to convert between a list and a tibble, so thanks.

But unfortunately keep_empty = TRUE failed to keep my missing regions. It just gave me the error Error in unnest_longer(., col = value, keep_empty = TRUE) : unused argument (keep_empty = TRUE)

The latest version of tidyr is 1.3 i think. Try upgrading to that.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.