Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ##################################################################
- ## Function ##
- ##################################################################
- fish <- function(l, keys, .dflt = NULL, missing.rm = FALSE) {
- if(!is.list(keys)) stop("The keys to search should be given as a list.")
- modified_names <- names(keys) %||% rep("", length(keys)) %>%
- str_replace("^$", as.character(NA))
- old_names <- map_chr(keys, get_very_last)
- new_names <- coalesce(modified_names, old_names)
- new_list <- keys %>%
- purrr::map(~purrr::pluck(l, ., .default = .dflt)) %>%
- set_names(new_names)
- if(missing.rm) return(compact(new_list))
- new_list
- }
- get_very_last <- function(l) {
- last_value <- l[[length(l)]]
- if(length(last_value) != 1) return(get_very_last(last_value))
- last_value
- }
- #################################################################
- ## Usage ##
- #################################################################
- # Define all the keys you want to keep as a list
- # You can optionally define a new name, otherwise the deepest name is used
- keys_to_keep <- list(
- "id",
- "amount_due",
- "amount_paid",
- "amount_remaining",
- "currency",
- "charge",
- "lines",
- "status",
- line_count = list("lines", "total_count"),
- plan_id = list("lines", "data", 1, "plan", "id"),
- plan_name = list("lines", "data", 1, "plan", "name"),
- period = list("lines", "data", 1, "period"),
- item_id = list("lines", "data", 1, "subscription_item"),
- "date",
- "due_date"
- )
- invoices <- invoice_raw_data %>%
- map(fish, keys_to_keep, missing.rm = TRUE)
Add Comment
Please, Sign In to add comment