# Helper function to get information from nested JSON
get_value <- function(x, ...) {
value <- purrr::pluck(x, ..., .default = NA_character_)
as.character(value[[1]])
}
# Getting the laureate's name
get_name <- function(x) {
name <- get_value(x, "fullName", "en")
if (is.na(name)) {
name <- get_value(x, "orgName", "en")
}
name
}
# Getting birthplace country
get_country <- function(x) {
country <- get_value(x, "birth", "place", "countryNow", "en")
if (is.na(country)) {
country <- get_value(x, "birth", "place", "country", "en")
}
country
}
# Creating a table of laureates
laureates_df <- tibble(
id = map_chr(laureates, ~ get_value(.x, "id")),
name = map_chr(laureates, get_name),
gender = map_chr(laureates, ~ get_value(.x, "gender")),
birth_country = map_chr(laureates, get_country),
birth_date = map_chr(laureates, ~ get_value(.x, "birth", "date")),
death_date = map_chr(laureates, ~ get_value(.x, "death", "date")),
prizes = map(laureates, ~ purrr::pluck(.x, "nobelPrizes", .default = list()))
)
# Creating one row per laureate and prize
prize_df <- laureates_df %>%
unnest_longer(prizes, values_to = "prize") %>%
mutate(
award_year = map_int(prize, ~ as.integer(get_value(.x, "awardYear"))),
category = map_chr(prize, ~ get_value(.x, "category", "en")),
motivation = map_chr(prize, ~ get_value(.x, "motivation", "en")),
date_awarded = map_chr(prize, ~ get_value(.x, "dateAwarded"))
)