Pulling in BEA API Data Into R

I have begun writing a script that I would like to pass on.  It pulls in GDP by MSA data using the BEA’s API into R.  This is the beginning of an analysis I am hoping to preform.  Hopefully others find this helpful.

# Load the needed libraries

# Set my BEA API key
bea.api.url <- "http://www.bea.gov/api/data"

# Read in the FIPS codes for the MSA's
msa = read.csv("bea_msa_fips.csv",head=TRUE,sep=",")
fips = msa$FIPS

# Create data frame to hold the API results
df <- data.frame()

# Loop through the MSA's to request the MSA GDP
for (i in 1:length(fips))
# Make the request to the API
req <- paste("http://www.bea.gov/api/data/?&UserID=", bea.api.key, "&method=GetData&datasetname=RegionalData&KeyCode=GDP_MP&GeoFIPS=", fips[i], "&ResultFormat=json", sep="")

# Parse the JSON response
res <- fromJSON(getURL(req))

# Since there are multiple years in the response we need to loop through them
for (j in 1:length(res$BEAAPI$Results$Data))
# Append the API result to the data frame
r <- as.data.frame(res$BEAAPI$Results$Data[j])
df <- rbind(df,r)

msa.gdp <- dcast(df, GeoName + GeoFips ~ TimePeriod, value.var="DataValue")

If you are interested in using this you will need this csv.


8 thoughts on “Pulling in BEA API Data Into R

  1. James L says:

    This is really great Andrew. Very useful and exactly the type of tutorial I was looking for. Thanks for taking the time to make it public.


  2. Rob Wiederstein says:

    Good stuff. Still baffled why there’s not more interest in an API for the BEA. Most of the stuff I do involves an economic indicator at the county level. Just getting data into R can be pretty frustrating. Thanks for the work.

    • Mike Silva says:

      I totally agree Rob! The BLS also has an API that I use. I just got my blsAPI package submitted to CRAN. Perhaps I should write a package for the BEA API.

  3. Rob Wiederstein says:

    Might try it. Saw your repo on the FRED API on github and forked it. Between FRED, BLS and the BEA, that should keep me plenty busy. Have you done anything with Annie E. Casey Kids Count or County Health Rankings? If they have an API, I can’t find it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s