Skip to content

Instantly share code, notes, and snippets.

@WesIngwersen
Last active October 30, 2023 18:19
Show Gist options
  • Save WesIngwersen/e826e8bd1be62acc7b7885127a88f0ad to your computer and use it in GitHub Desktop.
Save WesIngwersen/e826e8bd1be62acc7b7885127a88f0ad to your computer and use it in GitHub Desktop.
State Import Export Data for a Given Year from StateIO Models
---
title: "State Import Export Data for a Given Year from StateIO Models"
author: "Wesley Ingwersen"
date: "2023-10-30"
output:
md_document:
variant: gfm
params:
year: 2020
---
This script loads a pre-created dataset from the [stateior](http://www.github.com/usepa/stateior) package with State IO models to access data on state interregional (between states) and international imports/exports for a given year specified in a parameter. The year must be present in the data provided by the package version being used.
Load the stateior package, store the version number and display the package information.
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(stateior)
version <- as.character(packageVersion("stateior"))
packageDescription("stateior")
year <- params$year
```
Load the Two Region Use with Trade dataset for the given year.
Loop through all states.
For each state, extract the columns of the dataset representing interregional import, export and net trade, as well as international import and export.
Flip sign on international imports because positive imports show as negative in the Use table.
Write the table out to csv in the local directory.
```{r}
TwoRegionUse_ls <- loadStateIODataFile(paste0("TwoRegion_Summary_UsewithTrade_",params$year))
InterregionalTrade <- data.frame()
for (state in state.name) {
SoI2SoIUse <- TwoRegionUse_ls[[state]][["SoI2SoI"]]
InterregionalTradeSummary <- cbind.data.frame(state,
params$year,
row.names(SoI2SoIUse),
SoI2SoIUse[,"InterregionalImports"],
SoI2SoIUse[,"InterregionalExports"],
SoI2SoIUse[,"NetExports"],
SoI2SoIUse[,"F050"], #F050 is Imports in Final Demand of Use table
SoI2SoIUse[,"F040"] #F040 is Exports in Final Demand of Use table
)
colnames(InterregionalTradeSummary) <-
c(
"State",
"Year",
"Commodity",
"InterregionalImports",
"InterregionalExports",
"NetExports",
"InternationalImports",
"InternationalExports"
)
#Flip sign on international imports because positive imports show as negative in the Use table
InterregionalTradeSummary[,"InternationalImports"] <- -InterregionalTradeSummary[,"InternationalImports"]
InterregionalTrade <- rbind(InterregionalTrade,InterregionalTradeSummary)
}
filetowrite <- paste0("StateImportExport_",params$year,"_stateior_v",version,".csv")
write.csv(InterregionalTrade,filetowrite,row.names = FALSE)
print(paste("Wrote data to",filetowrite))
# Clean up
rm(TwoRegionUse_ls)
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment