Part 0: Setup

# Clear the workspace
  rm(list = ls()) # Clear environment
  gc()            # Clear unused memory
##          used (Mb) gc trigger (Mb) limit (Mb) max used (Mb)
## Ncells 518438 27.7    1146604 61.3         NA   669294 35.8
## Vcells 951569  7.3    8388608 64.0      16384  1839842 14.1
  cat("\f")       # Clear the console
  dev.off         # Clear the charts
## function (which = dev.cur()) 
## {
##     if (which == 1) 
##         stop("cannot shut down device 1 (the null device)")
##     .External(C_devoff, as.integer(which))
##     dev.cur()
## }
## <bytecode: 0x7fd92f8f6ea8>
## <environment: namespace:grDevices>
# Create a list of all packages to be used
  packages <- c("bea.R",
                "tidyverse",
                "ggplot2",
                "knitr")
  
#Install Packages
  for (i in 1:length(packages)) {# Iterate through each package in the 'packages' vector.
  if (!packages[i] %in% rownames(installed.packages())) {#check if package is installed
    install.packages(packages[i], #install package if it isn't already
                     repos = "http://cran.rstudio.com/",
                     dependencies = TRUE)}
  library(packages[i], character.only = TRUE)} # Load the package into the R session.
## 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.
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.1     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ ggplot2   3.4.4     ✔ tibble    3.2.1
## ✔ lubridate 1.9.2     ✔ tidyr     1.3.0
## ✔ purrr     1.0.1     
## ── 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
# Remove packages and i
  rm(packages, i)

# Use bea key (kept in hidden chunk)

Searching for the Data

# Look at all available datasets
  kable(beaSets(beaKey = beaKey))
## No encoding supplied: defaulting to UTF-8.
DatasetName DatasetDescription
NIPA Standard NIPA tables
NIUnderlyingDetail Standard NI underlying detail tables
MNE Multinational Enterprises
FixedAssets Standard Fixed Assets tables
ITA International Transactions Accounts
IIP International Investment Position
InputOutput Input-Output Data
IntlServTrade International Services Trade
IntlServSTA International Services Supplied Through Affiliates
GDPbyIndustry GDP by Industry
Regional Regional data sets
UnderlyingGDPbyIndustry Underlying GDP by Industry
APIDatasetMetaData Metadata about other API datasets
# Use NIPA dataframe
  kable(beaParams(beaKey = beaKey, "NIPA"))
## No encoding supplied: defaulting to UTF-8.
ParameterName ParameterDataType ParameterDescription ParameterIsRequiredFlag ParameterDefaultValue MultipleAcceptedFlag AllValue
Frequency string A - Annual, Q-Quarterly, M-Monthly 1 1
ShowMillions string A flag indicating that million-dollar data should be returned. 0 N 0
TableID integer The standard NIPA table identifier 0 NA 0
TableName string The new NIPA table identifier 0 NA 0
Year integer List of year(s) of data to retrieve (X for All) 1 1 X
# Search for GDP
###
#Found using URL: https://apps.bea.gov/iTable/?reqid=19&step=2&isuri=1&categories=survey#eyJhcHBpZCI6MTksInN0ZXBzIjpbMSwyLDNdLCJkYXRhIjpbWyJjYXRlZ29yaWVzIiwiU3VydmV5Il0sWyJOSVBBX1RhYmxlX0xpc3QiLCI1Il1dfQ==
###

  #Current Gross Domestic Product
  kable(head(beaSearch("Table 1.1.5. Gross Domestic Product", beaKey = beaKey)))
## 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("Table 1.1.5. Gross Domestic Product", beaKey = beaKey):
## Regional metadata is missing from
## /Library/Frameworks/R.framework/Versions/4.2/Resources/library/beaR/data and
## may be locked for updating on the BEA API; searching national metadata only.
SeriesCode RowNumber LineDescription LineNumber ParentLineNumber Tier Path TableID DatasetName TableName ReleaseDate NextReleaseDate MetaDataUpdated Account apiCall
A191RC 10 Gross domestic product 1 0 0 1 T10105 NIPA Table 1.1.5. Gross Domestic Product Feb 28 2019 8:30AM Mar 28 2019 8:30AM 2019-03-06T10:13:29.923 National beaGet(list(‘UserID’ = ‘[your_key]’, ‘Method’ = ‘GetData’, ‘DatasetName’ = ‘NIPA’, ‘TableName’ = ‘T10105’, …))
B009RC 100 Structures 10 9 4 1.7.8.9.10 T10105 NIPA Table 1.1.5. Gross Domestic Product Feb 28 2019 8:30AM Mar 28 2019 8:30AM 2019-03-06T10:13:29.923 National beaGet(list(‘UserID’ = ‘[your_key]’, ‘Method’ = ‘GetData’, ‘DatasetName’ = ‘NIPA’, ‘TableName’ = ‘T10105’, …))
Y033RC 110 Equipment 11 9 4 1.7.8.9.11 T10105 NIPA Table 1.1.5. Gross Domestic Product Feb 28 2019 8:30AM Mar 28 2019 8:30AM 2019-03-06T10:13:29.923 National beaGet(list(‘UserID’ = ‘[your_key]’, ‘Method’ = ‘GetData’, ‘DatasetName’ = ‘NIPA’, ‘TableName’ = ‘T10105’, …))
Y001RC 120 Intellectual property products 12 9 4 1.7.8.9.12 T10105 NIPA Table 1.1.5. Gross Domestic Product Feb 28 2019 8:30AM Mar 28 2019 8:30AM 2019-03-06T10:13:29.923 National beaGet(list(‘UserID’ = ‘[your_key]’, ‘Method’ = ‘GetData’, ‘DatasetName’ = ‘NIPA’, ‘TableName’ = ‘T10105’, …))
A011RC 130 Residential 13 8 3 1.7.8.13 T10105 NIPA Table 1.1.5. Gross Domestic Product Feb 28 2019 8:30AM Mar 28 2019 8:30AM 2019-03-06T10:13:29.923 National beaGet(list(‘UserID’ = ‘[your_key]’, ‘Method’ = ‘GetData’, ‘DatasetName’ = ‘NIPA’, ‘TableName’ = ‘T10105’, …))
A014RC 140 Change in private inventories 14 7 2 1.7.14 T10105 NIPA Table 1.1.5. Gross Domestic Product Feb 28 2019 8:30AM Mar 28 2019 8:30AM 2019-03-06T10:13:29.923 National beaGet(list(‘UserID’ = ‘[your_key]’, ‘Method’ = ‘GetData’, ‘DatasetName’ = ‘NIPA’, ‘TableName’ = ‘T10105’, …))
  # Real Gross Domestic Product
  kable(head(beaSearch("Table 1.1.6. Real Gross Domestic Product, Chained Dollars", 
                       beaKey = beaKey)))
## 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("Table 1.1.6. Real Gross Domestic Product, Chained
## Dollars", : Regional metadata is missing from
## /Library/Frameworks/R.framework/Versions/4.2/Resources/library/beaR/data and
## may be locked for updating on the BEA API; searching national metadata only.
SeriesCode RowNumber LineDescription LineNumber ParentLineNumber Tier Path TableID DatasetName TableName ReleaseDate NextReleaseDate MetaDataUpdated Account apiCall
A191RX 10 Gross domestic product 1 0 1 T10106 NIPA Table 1.1.6. Real Gross Domestic Product, Chained Dollars Feb 28 2019 8:30AM Mar 28 2019 8:30AM 2019-03-06T10:13:29.923 National beaGet(list(‘UserID’ = ‘[your_key]’, ‘Method’ = ‘GetData’, ‘DatasetName’ = ‘NIPA’, ‘TableName’ = ‘T10106’, …))
B009RX 100 Structures 10 0 10 T10106 NIPA Table 1.1.6. Real Gross Domestic Product, Chained Dollars Feb 28 2019 8:30AM Mar 28 2019 8:30AM 2019-03-06T10:13:29.923 National beaGet(list(‘UserID’ = ‘[your_key]’, ‘Method’ = ‘GetData’, ‘DatasetName’ = ‘NIPA’, ‘TableName’ = ‘T10106’, …))
Y033RX 110 Equipment 11 0 11 T10106 NIPA Table 1.1.6. Real Gross Domestic Product, Chained Dollars Feb 28 2019 8:30AM Mar 28 2019 8:30AM 2019-03-06T10:13:29.923 National beaGet(list(‘UserID’ = ‘[your_key]’, ‘Method’ = ‘GetData’, ‘DatasetName’ = ‘NIPA’, ‘TableName’ = ‘T10106’, …))
Y001RX 120 Intellectual property products 12 0 12 T10106 NIPA Table 1.1.6. Real Gross Domestic Product, Chained Dollars Feb 28 2019 8:30AM Mar 28 2019 8:30AM 2019-03-06T10:13:29.923 National beaGet(list(‘UserID’ = ‘[your_key]’, ‘Method’ = ‘GetData’, ‘DatasetName’ = ‘NIPA’, ‘TableName’ = ‘T10106’, …))
A011RX 130 Residential 13 0 13 T10106 NIPA Table 1.1.6. Real Gross Domestic Product, Chained Dollars Feb 28 2019 8:30AM Mar 28 2019 8:30AM 2019-03-06T10:13:29.923 National beaGet(list(‘UserID’ = ‘[your_key]’, ‘Method’ = ‘GetData’, ‘DatasetName’ = ‘NIPA’, ‘TableName’ = ‘T10106’, …))
A014RX 140 Change in private inventories 14 0 14 T10106 NIPA Table 1.1.6. Real Gross Domestic Product, Chained Dollars Feb 28 2019 8:30AM Mar 28 2019 8:30AM 2019-03-06T10:13:29.923 National beaGet(list(‘UserID’ = ‘[your_key]’, ‘Method’ = ‘GetData’, ‘DatasetName’ = ‘NIPA’, ‘TableName’ = ‘T10106’, …))

Importing Data

# Creat a specs list to use inside beaGet

  #current GDP specs
  current_specs <- list(
    "UserID" = beaKey, # Set up API key
    "Method" = "GetData", # Method
    "datasetname" = "NIPA", # Specify dataset
    "TableName" = "T10105", # Specify table within the dataset
    "Frequency" = "A", # Specify annual data
    "Year" = "X", # Show data for all years
    'ResultFormat' = 'json', # Specify format
    "ShowMillions" = "Y"
  )
  
  #Real GDP specs
  real_specs <- list(
    "UserID" = beaKey, # Set up API key
    "Method" = "GetData", # Method
    "datasetname" = "NIPA", # Specify dataset
    "TableName" = "T10106", # Specify table within the dataset
    "Frequency" = "A", # Specify annual data
    "Year" = "X", # Show data for all years
    'ResultFormat' = 'json', # Specify format
    "ShowMillions" = "Y"
  )

# Import the data
  currentGDP <- beaGet(current_specs, asWide = FALSE) #current GDP
## No encoding supplied: defaulting to UTF-8.
  realGDP <- beaGet(real_specs, asWide = FALSE) #current GDP
## No encoding supplied: defaulting to UTF-8.

Construct Data Set

  #Filter values for current
  filtered_current <- 
    currentGDP[currentGDP$LineDescription == 'Gross domestic product', ]
  
  #Filter values for real GDP
  filtered_real <- 
    realGDP[realGDP$LineDescription == 'Gross domestic product', ]
  
  #Create variable for Real GDP
  filtered_real$RGDP <- filtered_real$DataValue

  #Make a new table to store data
  GDPdata <- data.frame(TimePeriod = filtered_current$TimePeriod, 
                    DataValue = filtered_current$DataValue)
  
  #Rename TimePeriod to Year
  GDPdata$Year <- as.numeric(GDPdata$TimePeriod)
  GDPdata$TimePeriod <- NULL
  
  #Rename DataValue to GDP (current GDP)
  GDPdata$GDP <- GDPdata$DataValue
  GDPdata$DataValue <- NULL
  
  #Add Real GDP
  GDPdata$RGDP <- filtered_real$RGDP
  
  kable(head(GDPdata))
Year GDP RGDP
1929 104556 1191124
1930 92160 1089785
1931 77391 1019977
1932 59522 888414
1933 57154 877431
1934 66800 972263

Create Graphs

GDP_plot <- ggplot(GDPdata, aes(x = Year, y = GDP, group = 1)) +
  geom_line() +  
  scale_x_continuous(breaks = seq(1929, 2022, by = 10)) +
  scale_y_continuous(breaks = seq(0, max(GDPdata$GDP), by = 5000000), labels = scales::comma) +  # Specify the breaks and use comma formatting for labels
  
  labs(x = "Year",
       y = "GDP ($ billions)",
       title = "US GDP (Billions $)")

print(GDP_plot)

RGDP_plot <- ggplot(GDPdata, aes(x = Year, y = RGDP, group = 1)) +
  geom_line() +  
  scale_x_continuous(breaks = seq(1929, 2022, by = 10)) +
  scale_y_continuous(breaks = seq(0, max(GDPdata$GDP), by = 5000000), labels = scales::comma) +  # Specify the breaks and use comma formatting for labels
  
  labs(x = "Year",
       y = "Real GDP ($ billions)",
       title = "US Real GDP (Billions $)")


print(RGDP_plot)