Lee Jim
Lee Jim

Reputation: 405

Convert list to tibble in R with NULL values

library(tidyverse)

event <- list(
  reportId = 157250,
  eventId = 4580,
  country = "Moldova",
  disease = "African swine fever",
  subType = NULL
)

event %>% as_tibble()

An error raised:

There are thousands of events list like this, is any method to get a tibble object properly.

Upvotes: 1

Views: 675

Answers (3)

Michael Henry
Michael Henry

Reputation: 631

I have the same requirement; I have a list obtained from the FlightAware API (converted from JSON) that contains NULLs.

The solution by @manuela-benary did not work straight away because the response includes a nested array of alternatives; here is the specification for the response from the API documentation:

{
  "icao": "string",
  "iata": "string",
  "callsign": "string",
  "name": "string",
  "country": "string",
  "location": "string",
  "phone": "string",
  "shortname": "string",
  "url": "string",
  "wiki_url": "string",
  "alternatives": [
    {
      "icao": "string",
      "iata": "string",
      "callsign": "string",
      "name": "string",
      "country": "string",
      "location": "string",
      "phone": "string",
      "shortname": "string",
      "url": "string",
      "wiki_url": "string"
    }
  ]
}

This simply required running Manuela's code on the alternatives list first, then NULLing that member of the response, and then running the code on the original list. The two sets of results can then be row_bind()ed together.

Upvotes: 0

Manuela Benary
Manuela Benary

Reputation: 11

You can circumvent this by running the following steps:

event %>% 
  enframe() %>% # long format with all elements as lists
  unnest("value", keep_empty = TRUE) %>% # transform into elementary data
  pivot_wider(names_from = "name", values_from = "value") # make wide format with all columns

Upvotes: 1

Lee Jim
Lee Jim

Reputation: 405

use map_df can generate a tibble object, however, the column with NULL missed.

event %>% map_df(.f = ~.x)

Upvotes: 0

Related Questions