::install_github("keberwein/blscrapeR") # install package from GitHub
devtoolslibrary(blscrapeR)
set_bls_key("YOUR_KEY_IN_QUOTATIONS")
# First time, reload your enviornment so you can use the key without restarting R.
readRenviron("~/.Renviron")
# You can check it with:
Sys.getenv("BLS_KEY")
Inflation Adjustments
Please use all code samples responsibly - these are samples and likely require adjustments to work correctly for your specific needs. Read through the documentation and comments to understand any caveats or limitations of the code and/or data and follow-up with the code author or Code Library admins (code_library@urban.org) if you have questions on how to adapt the sample to your specific use case.
Purpose: This is sample code for using the blscrapeR
library to inflation adjust numbers to a base year (for example to 2023 dollars). blscrapeR
provides a tidy API wrapper for the Bureau of Labor Statistics (BLS) data. For more information see the package documentation.
Data: This code is relevant for any dollar variables that need to be adjusted for inflation such as median household income or median home price.
Installation: While you don’t need an API key from BLS to run the code below, getting one will increase your daily rate limit (the number of times a day that you can pull data from the API) from 25 to 500. If you plan to run the code repeatedly, I would recommend getting one here. You can add it to your R environment with the code below:
Author: Amy Rogin (February 2024)
5-year ACS data is inflation adjusted to the last year of the panel (so 2018-2022 ACS data is inflation adjusted to 2022 dollars)
library(blscrapeR) # library with inflation data
library(tidyverse)
# get an inflation adjustment table with base year 2023
# note: you can only download a limited number of years at once so need to make
# multiple calls and bind the rows together
<- bls_api(seriesid = "CUSR0000SA0", startyear = 2002, endyear = 2011) %>%
inflation_adjustment bind_rows(bls_api(seriesid = "CUSR0000SA0", startyear = 2012, endyear = 2017)) %>%
bind_rows(bls_api(seriesid = "CUSR0000SA0", startyear = 2018, endyear = 2023)) %>%
group_by(year) %>%
summarize(value = mean(value))
# get 2023 CPI
<- inflation_adjustment %>%
cpi_2023 filter(year == 2023) %>%
pull(value)
# calculate inflation value
<- inflation_adjustment %>%
inflation_adjustment # this calculates the multiplier for past years to get
# to 2023 dollars
mutate(multiplier = cpi_2023 / value) %>%
select(year, multiplier)
# read in your data
# in this example we have data for 2007 through 2023 that
# we need inflation adjusted
<- read_csv("sample_data.csv")) %>%
sample_data # join inflation adjustment by year
# so 2007 data is matched to the 2007 inflation adjustment value
::left_join(inflation_adjustment, by = "year") %>%
tidylog# multiply the variable of interest by 'multiplier' to adjust to 2023 dollars
mutate(across(c("median_hh_income", "median_home_price"), ~.*multiplier))