https://github.com/us-bea/bea.R

1 SetUp

# Clear the workspace
  rm(list = ls()) # Clear environment -remove all files from your workspace
  gc()            # Clear unused memory
##           used (Mb) gc trigger (Mb) limit (Mb) max used (Mb)
## Ncells  551262 29.5    1224912 65.5         NA   700242 37.4
## Vcells 1021331  7.8    8388608 64.0      32768  1963400 15.0
  cat("\f")       # Clear the console
#  graphics.off()  # Clear all graphs

2 Library

library("bea.R")        #  for getting data 
## Loading required package: data.table
## Note: As of February 2018, beaGet() requires 'TableName' for NIPA and NIUnderlyingDetail data instead of 'TableID.' See https://github.us-bea/bea.R for details.
library("tidyverse")    #  data manipulation/wrangling
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.1     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.1
## ✔ purrr     1.0.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::between()     masks data.table::between()
## ✖ dplyr::filter()      masks stats::filter()
## ✖ dplyr::first()       masks data.table::first()
## ✖ lubridate::hour()    masks data.table::hour()
## ✖ lubridate::isoweek() masks data.table::isoweek()
## ✖ dplyr::lag()         masks stats::lag()
## ✖ dplyr::last()        masks data.table::last()
## ✖ lubridate::mday()    masks data.table::mday()
## ✖ lubridate::minute()  masks data.table::minute()
## ✖ lubridate::month()   masks data.table::month()
## ✖ lubridate::quarter() masks data.table::quarter()
## ✖ lubridate::second()  masks data.table::second()
## ✖ purrr::transpose()   masks data.table::transpose()
## ✖ lubridate::wday()    masks data.table::wday()
## ✖ lubridate::week()    masks data.table::week()
## ✖ lubridate::yday()    masks data.table::yday()
## ✖ lubridate::year()    masks data.table::year()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

3 My Unique BEA API key

Replace with your own unique key that you got on signup.

my_beaKey   <- '293963AB-94AA-4234-AF30-43EB482D85CB'

4 Search for the data tables

?beaSearch
beaSearch(searchTerm = 'GDP', 
          beaKey     = my_beaKey, 
          asHtml     = TRUE
          )
## Creating first-time local copy of metadata for all datasets - only done once.
## Datasets will be updated only if timestamps indicate metadata obsolete in future searches,
## and only obsolete metadata sets will be updated (it's faster this way).
## 
## No encoding supplied: defaulting to UTF-8.
## Warning in beaSearch(searchTerm = "GDP", beaKey = my_beaKey, asHtml = TRUE):
## Regional metadata is missing from
## /Library/Frameworks/R.framework/Versions/4.4-arm64/Resources/library/beaR/data
## and may be locked for updating on the BEA API; searching national metadata
## only.

5 Load the data tables

# beaGet(list('UserID' = '[your_key]', 'Method' = 'GetData', 'DatasetName' = 'NIPA', 'TableName' = 'T10705', ...))

?beaGet
my_beaSpecs <- list(
    'UserID'       = my_beaKey ,
    'Method'       = 'GetData',
    'datasetname'  = 'NIPA',
    'TableName'    = 'T10705', 
    'Frequency'    = 'Q',
    'Year'         = 'X',
    'ResultFormat' = 'json'
)

beaPayload <- beaGet(beaSpec = my_beaSpecs)
## No encoding supplied: defaulting to UTF-8.

6 Transform the wide data into long form

beaLong    <- beaGet(beaSpec = my_beaSpecs, 
                     asWide  = FALSE
                     )
## No encoding supplied: defaulting to UTF-8.
table(beaLong$LineDescription)
## 
##                                                         Average of GDP and GDI 
##                                                                            309 
##                                       Business current transfer payments (net) 
##                                                                            310 
##                                                 Capital consumption allowances 
##                                                                            310 
##                        Contributions for government social insurance, domestic 
##                                                                            310 
## Corporate profits with inventory valuation and capital consumption adjustments 
##                                                                            309 
##                                      Current surplus of government enterprises 
##                                                                            262 
##                                                              Domestic business 
##                                                                            310 
##                                                 Equals: Gross national product 
##                                                                            309 
##                                                        Equals: National income 
##                                                                            309 
##                                                   Equals: Net national product 
##                                                                            309 
##                                                        Equals: Personal income 
##                                                                            310 
##                                                             General government 
##                                                                            310 
##                                                                     Government 
##                                                                            310 
##                                                         Government enterprises 
##                                                                            310 
##                                                    Gross domestic income (GDI) 
##                                                                            309 
##                                                   Gross domestic product (GDP) 
##                                                                            310 
##                                                   Gross national factor income 
##                                                                            309 
##                                                          Gross national income 
##                                                                            309 
##                                                    Households and institutions 
##                                                                            310 
##                                           Less: Capital consumption adjustment 
##                                                                            310 
##                                             Less: Consumption of fixed capital 
##                                                                            310 
##                                 Less: Income payments to the rest of the world 
##                                                                            309 
##                                                  Less: Statistical discrepancy 
##                                                                            309 
##                                                            Net domestic income 
##                                                                            309 
##                                                           Net domestic product 
##                                                                            310 
##                                                         Net domestic purchases 
##                                                                            310 
##                              Net interest and miscellaneous payments on assets 
##                                                                            310 
##                                                     Net national factor income 
##                                                                            309 
##                               Plus: Income receipts from the rest of the world 
##                                                                            309 
##                                       Plus: Personal current transfer receipts 
##                                                                            310 
##                                       Plus: Personal income receipts on assets 
##                                                                            310 
##                                                                        Private 
##                                                                            310 
##                                 Statistical discrepancy as a percentage of GDP 
##                                                                            309 
##                                 Taxes on production and imports less subsidies 
##                                                                            310

7 Graph

df <- beaLong |> filter(LineDescription =="Gross domestic product (GDP)")

df$year <- substring(text  = df$TimePeriod,
                     first = 1, 
                     last  = 4
                     )

ggplot(data    = df, 
       mapping = aes(x = year, 
                     y = DataValue/1000000)
       ) + geom_line() + labs(title = "US GDP over time", 
                              x     = "Year", 
                              y     = "GDP (in trillions)"
                              ) +
  theme(axis.text.x = element_text(angle=90,
                                   vjust=.5)
        )

7.1 Transform the data

?aggregate

# Aggregate the data by year and calculate the mean of DataValue
df_annual <- aggregate(DataValue ~ year, 
                       data = df, 
                       FUN = mean)

ggplot(data    = df_annual, 
       mapping = aes(x = as.numeric(year), 
                     y = DataValue/1000000)
       ) + geom_line() + labs(title = "US GDP over time", 
                              x     = "Year", 
                              y     = "GDP (in trillions)"
                              ) +
  theme(axis.text.x = element_text(angle=90,
                                   vjust=.5)
        )