I'm trying to get some data from an API from a Brazilian Regulator.
In the sandbox version, can only extract information from one day, but at the paid version you can choose the day
When I'm using a for loop to iterate through a list of days I'm getting a error in the day in the code below, the error is:
Error in `fn()`:
! In row 1, can't recycle input of size 45 to size 44.
Error in `fn()`:
! In row 1, can't recycle input of size 45 to size 44.
---
Backtrace:
1. base::source(...)
7. tidyr:::unnest.data.frame(., everything())
8. tidyr::unchop(data, any_of(cols), keep_empty = keep_empty, ptype = ptype)
9. tidyr:::df_unchop(cols, ptype = ptype, keep_empty = keep_empty)
10. purrr::reduce(x_sizes, unchop_sizes2)
11. purrr:::reduce_impl(.x, .f, ..., .init = .init, .dir = .dir)
12. tidyr (local) fn(out, elt, ...)
<error/rlang_error>
Error in `fn()`:
! In row 1, can't recycle input of size 45 to size 44.
---
Backtrace:
x
1. +-base::source(...)
2. | +-base::withVisible(eval(ei, envir))
3. | \-base::eval(ei, envir)
4. | \-base::eval(ei, envir)
5. +-... %>% unnest(everything()) at ~/.active-rstudio-document:39:0
6. +-tidyr::unnest(., everything())
7. \-tidyr:::unnest.data.frame(., everything())
8. \-tidyr::unchop(data, any_of(cols), keep_empty = keep_empty, ptype = ptype)
9. \-tidyr:::df_unchop(cols, ptype = ptype, keep_empty = keep_empty)
10. \-purrr::reduce(x_sizes, unchop_sizes2)
11. \-purrr:::reduce_impl(.x, .f, ..., .init = .init, .dir = .dir)
12. \-tidyr (local) fn(out, elt, ...)
13. \-rlang::abort(glue("In row {row}, can't recycle input of size {x} to size {y}."))
I presume the error is from the manner that I'm extracting the data from the JSON response. I'm open to suggestions of different ways to do this. Thank you in advance.
Code below:
#access information obtained when signed up at API ANBIMA - https://admin-developers.anbima.com.br/api-portal/en/user/register
client_id <- 'XXXXXXXXXXXX'
client_secret <- 'YYYYYYYYYYY'
token_anbima <- base64_enc(str_c(client_id, ':', client_secret))
resposta_anbima <- POST("https://api.anbima.com.br/oauth/access-token",
add_headers("Authorization" = str_c("Basic ", token_anbima)),
body = list(grant_type = "client_credentials"),
encode = 'form')
access_token <- str_sub(content(resposta_anbima, "text"), start = 18, end = 29)
data_tpf <- '2023-01-04'
info <- GET(str_c('https://api.anbima.com.br/feed/precos-indices/v1/titulos-publicos/mercado-secundario-TPF?data=',
data_tpf),
add_headers("client_id" = client_id,
"access_token" = access_token))
dados_tpf <- enframe(unlist(content(info)))
dados_tpf_2 <- pivot_wider(dados_tpf, names_from=name, values_from=value, values_fn=list) %>%
unnest(everything())