Guest User

Untitled

a guest
Jan 17th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. ##################################################################
  2. ## Function ##
  3. ##################################################################
  4.  
  5. fish <- function(l, keys, .dflt = NULL, missing.rm = FALSE) {
  6. if(!is.list(keys)) stop("The keys to search should be given as a list.")
  7.  
  8. modified_names <- names(keys) %||% rep("", length(keys)) %>%
  9. str_replace("^$", as.character(NA))
  10. old_names <- map_chr(keys, get_very_last)
  11. new_names <- coalesce(modified_names, old_names)
  12.  
  13. new_list <- keys %>%
  14. purrr::map(~purrr::pluck(l, ., .default = .dflt)) %>%
  15. set_names(new_names)
  16.  
  17. if(missing.rm) return(compact(new_list))
  18.  
  19. new_list
  20. }
  21.  
  22. get_very_last <- function(l) {
  23. last_value <- l[[length(l)]]
  24. if(length(last_value) != 1) return(get_very_last(last_value))
  25. last_value
  26. }
  27.  
  28.  
  29. #################################################################
  30. ## Usage ##
  31. #################################################################
  32.  
  33. # Define all the keys you want to keep as a list
  34. # You can optionally define a new name, otherwise the deepest name is used
  35.  
  36. keys_to_keep <- list(
  37. "id",
  38. "amount_due",
  39. "amount_paid",
  40. "amount_remaining",
  41. "currency",
  42. "charge",
  43. "lines",
  44. "status",
  45. line_count = list("lines", "total_count"),
  46. plan_id = list("lines", "data", 1, "plan", "id"),
  47. plan_name = list("lines", "data", 1, "plan", "name"),
  48. period = list("lines", "data", 1, "period"),
  49. item_id = list("lines", "data", 1, "subscription_item"),
  50. "date",
  51. "due_date"
  52. )
  53.  
  54. invoices <- invoice_raw_data %>%
  55. map(fish, keys_to_keep, missing.rm = TRUE)
Add Comment
Please, Sign In to add comment