Skip to content

Instantly share code, notes, and snippets.

@benjamin-chan
Last active June 13, 2022 23:12
Show Gist options
  • Save benjamin-chan/92e0c510b790e42a7a303964a872b165 to your computer and use it in GitHub Desktop.
Save benjamin-chan/92e0c510b790e42a7a303964a872b165 to your computer and use it in GitHub Desktop.
# Reference: https://www.bls.gov/developers/api_r.htm
library(magrittr)
library(dplyr)
library(devtools)
install_github("mikeasilva/blsAPI") # https://github.com/mikeasilva/blsAPI
library(rjson)
library(blsAPI)
payload <- list("seriesid" = c("CUUR0000SA0L1E"),
"startyear" = 2016,
"endyear" = 2021,
"annualaverage" = TRUE)
# payload <- list("seriesid" = c("CUUR0000SA0L1E"),
# "startyear" = 2016,
# "endyear" = 2021,
# "annualaverage" = TRUE,
# "registrationkey" = <BLS Public Data API Signature (Version 2.0)>)
response <- blsAPI(payload, 2)
json <- fromJSON(response)
df <- data.frame(year = character(),
period = character(),
periodName = character(),
value = character(),
stringsAsFactors = FALSE)
i <- 0
for (d in json$Results$series[[1]]$data) {
i <- i + 1
df[i, ] <- unlist(d)
}
df
df %>%
filter(periodName == "Annual") %>%
mutate(value = as.numeric(value)) %>%
mutate(inflationFactor = max(value) / value)
df %>%
filter(periodName != "Annual") %>%
mutate(value = as.numeric(value)) %>%
group_by(year) %>%
summarize(dataPoints = n(),
avgCalculated = mean(value)) %>%
ungroup() %>%
inner_join(df %>% filter(periodName == "Annual"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment