I have a list which I am turning into a dataframe. The list comes back from an API, and it contains some NULL
values. There are questions on SO on this topic here and here, but they either deal with dataframes, or in the case of the second link, the OP was encouraged to transform to a dataframe first. I want to keep the list structure.
I'm parsing it in the following fashion, here is some example data:
example <- list(
list(
ID = "1",
Name = "Joe",
Middle_name = "Alan",
Surname = "Smith"
),
list(
ID = "2",
Name = "Sarah",
Middle_name = NULL,
Surname = "Jones"
),
list(
ID = "3",
Name = "Robert",
Middle_name = "Myles",
Surname = "McDonnell"
)
)
N <- NA_character_
df <- tibble::tibble(
id = purrr::map_chr(example, .null = N, "ID"),
name = purrr::map_chr(example, .null = N, "Name"),
middle = purrr::map_chr(example, .null = N, "Middle_name"),
surname = purrr::map_chr(example, .null = N, "Surname")
)
> df
# A tibble: 3 x 4
id name middle surname
<chr> <chr> <chr> <chr>
1 1 Joe <NA> Smith
2 2 Sarah <NA> Jones
3 3 Robert <NA> McDonnell
It appears this issue has some history in the purrr repo, but when I use purrr functions like is_empty()
or compact()
, I either get an error or it doesn't work.
Does anyone know how I could achieve this, preferably by keeping to the tibble
& map_chr
method I'm using above?