NYC Data Science Academy| Blog
Bootcamps
Lifetime Job Support Available Financing Available
Bootcamps
Data Science with Machine Learning Flagship ๐Ÿ† Data Analytics Bootcamp Artificial Intelligence Bootcamp New Release ๐ŸŽ‰
Free Lesson
Intro to Data Science New Release ๐ŸŽ‰
Find Inspiration
Find Alumni with Similar Background
Job Outlook
Occupational Outlook Graduate Outcomes Must See ๐Ÿ”ฅ
Alumni
Success Stories Testimonials Alumni Directory Alumni Exclusive Study Program
Courses
View Bundled Courses
Financing Available
Bootcamp Prep Popular ๐Ÿ”ฅ Data Science Mastery Data Science Launchpad with Python View AI Courses Generative AI for Everyone New ๐ŸŽ‰ Generative AI for Finance New ๐ŸŽ‰ Generative AI for Marketing New ๐ŸŽ‰
Bundle Up
Learn More and Save More
Combination of data science courses.
View Data Science Courses
Beginner
Introductory Python
Intermediate
Data Science Python: Data Analysis and Visualization Popular ๐Ÿ”ฅ Data Science R: Data Analysis and Visualization
Advanced
Data Science Python: Machine Learning Popular ๐Ÿ”ฅ Data Science R: Machine Learning Designing and Implementing Production MLOps New ๐ŸŽ‰ Natural Language Processing for Production (NLP) New ๐ŸŽ‰
Find Inspiration
Get Course Recommendation Must Try ๐Ÿ’Ž An Ultimate Guide to Become a Data Scientist
For Companies
For Companies
Corporate Offerings Hiring Partners Candidate Portfolio Hire Our Graduates
Students Work
Students Work
All Posts Capstone Data Visualization Machine Learning Python Projects R Projects
Tutorials
About
About
About Us Accreditation Contact Us Join Us FAQ Webinars Subscription An Ultimate Guide to
Become a Data Scientist
    Login
NYC Data Science Acedemy
Bootcamps
Courses
Students Work
About
Bootcamps
Bootcamps
Data Science with Machine Learning Flagship
Data Analytics Bootcamp
Artificial Intelligence Bootcamp New Release ๐ŸŽ‰
Free Lessons
Intro to Data Science New Release ๐ŸŽ‰
Find Inspiration
Find Alumni with Similar Background
Job Outlook
Occupational Outlook
Graduate Outcomes Must See ๐Ÿ”ฅ
Alumni
Success Stories
Testimonials
Alumni Directory
Alumni Exclusive Study Program
Courses
Bundles
financing available
View All Bundles
Bootcamp Prep
Data Science Mastery
Data Science Launchpad with Python NEW!
View AI Courses
Generative AI for Everyone
Generative AI for Finance
Generative AI for Marketing
View Data Science Courses
View All Professional Development Courses
Beginner
Introductory Python
Intermediate
Python: Data Analysis and Visualization
R: Data Analysis and Visualization
Advanced
Python: Machine Learning
R: Machine Learning
Designing and Implementing Production MLOps
Natural Language Processing for Production (NLP)
For Companies
Corporate Offerings
Hiring Partners
Candidate Portfolio
Hire Our Graduates
Students Work
All Posts
Capstone
Data Visualization
Machine Learning
Python Projects
R Projects
About
Accreditation
About Us
Contact Us
Join Us
FAQ
Webinars
Subscription
An Ultimate Guide to Become a Data Scientist
Tutorials
Data Analytics
  • Learn Pandas
  • Learn NumPy
  • Learn SciPy
  • Learn Matplotlib
Machine Learning
  • Boosting
  • Random Forest
  • Linear Regression
  • Decision Tree
  • PCA
Interview by Companies
  • JPMC
  • Google
  • Facebook
Artificial Intelligence
  • Learn Generative AI
  • Learn ChatGPT-3.5
  • Learn ChatGPT-4
  • Learn Google Bard
Coding
  • Learn Python
  • Learn SQL
  • Learn MySQL
  • Learn NoSQL
  • Learn PySpark
  • Learn PyTorch
Interview Questions
  • Python Hard
  • R Easy
  • R Hard
  • SQL Easy
  • SQL Hard
  • Python Easy
Data Science Blog > R > Federal Spending and Congressional Representation

Federal Spending and Congressional Representation

Stephen Penrice
Posted on Nov 7, 2015
Contributed by Stephen Penrice. Stephen took NYC Data Science Academy 12 week full time Data Science Bootcamp program between Sept 23 to Dec 18, 2015. The post was based on his first class project(due at 2nd week of the program).

Project Information

Charting federal spending alongside congressional representation comprised my first project for the Fall 2015 NYC Data Science Academy Data Science Bootcamp, as presented on October 3, 2015. (Check out the video below for a recording of my presentation.)

The pedagogical purpose of this project was to practice using dplyr for data munging and ggplot2 for visualizations. In addition, I practiced using the XML and stringr packages to scrape and parse semi-structured text data into a form appropriate for analysis.

Introduction

This project creates some visualizations that relate federal government contract spending to the status of Congressional members representing those districts in which the contract work is performed. The key exhibits are plots that I like to think of as visual contingency tables. In particular, these visualizations juxtapose Representativesโ€™ seniority with the extent to which members serve on committees related to the department or agency issuing a contract or contracts to their districts. I look at Defense spending, for instance, in terms of membership on the Armed Services Committee. I also identify members of the Appropriations Committee: this is the committee responsible for the spending side the federal budget, and none of its members serve on any of the committees related to specific policy areas such as Armed Services or Natural Resources.

Gathering Data

All contract data are from FY 2015 and information on Congress is for the current (114th) Congress.

I realized rather late in the process that the timing of my data sources is a bit out of line, because the FY 2015 budget was approved in Fall 2014 while the 114th Congress began in January 2015. For the most part, I donโ€™t think is a huge problem, because committee assignments are fairly stable from one term to another. There are 67 first-term Representatives in the 114th Congress, and clearly they were not in office when the FY 2015 budget was approved, but isolating this group in the analysis actually leads to an interesting finding.

I downloaded the contract data manually from USAspending.gov. I limited my downloads to the 24 agencies listed under โ€œCFOโ€ in the โ€œAgencyโ€ drop-down menu. Because of the volume of the Defense Department data, I had to download data for each individual state one-by-one. This resulted in a total of 73 files containing 4.9 gbs of data.

In order to create a manageable file to use in the project, I've used the following function to open each downloaded file, extract desired fields, and place the pared-down data in a single file.

library(dplyr)

store.compact <- function(infilename, outfilename){
  temp <- read.table(infilename, header = TRUE, sep = ",", stringsAsFactors = FALSE)
  temp <- select(temp, 
                 unique_transaction_id, 
                 dollarsobligated,
                 maj_agency_cat,
                 vendorcountrycode,
                 state,
                 congressionaldistrict,
                 placeofperformancecongressionaldistrict,
                 placeofperformancezipcode) 
  
  write.table(temp, outfilename, 
              append = TRUE, 
              row.names = FALSE, 
              col.names = FALSE,
              sep = ",")
  rm(temp)
}

The following script calls the function. Here are the first several calls.

library(stringr)
library(dplyr)

source('~/nycdsa/proj_1_bootcamp/StoreCompactData.R')

system("rm ContractSpending.csv")

store.compact("contract_data/Data_Feed.csv","ContractSpending.csv")
store.compact("contract_data/Data_Feed-2.csv","ContractSpending.csv")
store.compact("contract_data/Data_Feed-3.csv","ContractSpending.csv")
store.compact("contract_data/Data_Feed-4.csv","ContractSpending.csv")
store.compact("contract_data/Data_Feed-5.csv","ContractSpending.csv")
store.compact("contract_data/Data_Feed-6.csv","ContractSpending.csv")
...

temp <- read.csv("ContractSpending.csv", header = FALSE, stringsAsFactors = FALSE)
saveRDS(temp,"contracts_raw.rds")

The following code downloads Congressional Committee data from clerk.house.gov and seniority data from pressgallery.house.gov.

library(stringr)
library(XML)
library(dplyr,warn.conflicts=FALSE)

url <- "http://clerk.house.gov/committee_info/oal.aspx"
RepData <- readHTMLTable(url, header = TRUE, stringsAsFactors = FALSE) %>% 
           data.frame() %>% tbl_df()
colnames(RepData) <- c("Member", "Committees")

url <- "http://pressgallery.house.gov/member-data/seniority"
SeniorData <- readHTMLTable(url, header = TRUE, stringsAsFactors = FALSE)[[1]] %>%
  select(., 2:4)
colnames(SeniorData) <- c('Member','PartyAndState','Terms')

Processing Data

1. Mapping Agency Codes

A first step in preparing the contract data for analysis is to map the 4-digit codes onto agency names. These names include both the long agency names from the source files and shorter, more convenient names created with the following function.

Short.Agency.Names <- function(code){

    if(code == 1200) return('Agriculture')
    else if(code == 1300) return('Commerce')
    else if(code == 1400) return('Interior')
    else if(code == 1500) return('Justice')
    else if(code == 1600) return('Labor')
    else if(code == 1900) return('State')
    else if(code == 2000) return('Treasury')
    else if(code == 2400) return('Personnel Management')
    else if(code == 2800) return('Social Security')
    else if(code == 3100) return('Nuclear Reg Comm')
    else if(code == 3600) return('Veterans Affairs')
    else if(code == 4700) return('GSA')
    else if(code == 4900) return('NSF')
    else if(code == 6800) return('EPA')
    else if(code == 6900) return('Transportation')
    else if(code == 7000) return('Homeland Security')
    else if(code == 7200) return('USAID')
    else if(code == 7300) return('Small Business Admin')
    else if(code == 7500) return('HHS')
    else if(code == 8000) return('NASA')
    else if(code == 8600) return('HUD')
    else if(code == 8900) return('Energy')
    else if(code == 9100) return('Education')
    else if(code == 9700) return('Defense')
}

The following code creates the actual mapping.

cstest <- readRDS("contracts_raw.rds")

# Create a mapping between agency codes and agency names, as implied by the contract data
# Each name appears twice in the raw files, so we pick the version that includes lowercase letters
agency_codes <- unique(cstest$V3)
lower <- agency_codes[str_detect(agency_codes,'[:lower:]+')]
lower <- array(lower)
agency_codes <- data.frame(id = str_sub(lower,1,4), Agency = str_sub(lower,7))

for(code in agency_codes$id){
  agency_codes$ShortName[agency_codes$id==code] <- Short.Agency.Names(code)
}
agency_codes$id <- as.character(agency_codes$id)
saveRDS(agency_codes,"agency_codes.rds")
rm(lower, agency_codes, code, Short.Agency.Names)

2. Cleaning contract data

Cleaning the contract data entails isolating agency codes into a separate field, adding field names (when putting data into a single file they have to be deleted), and eliminating obviously incorrect districts.

# Various cleaning tasks for contract data

# Create new field containing agency code
cstest <- mutate(cstest, Agency.Code = str_sub(V3,1,4)) 
# Add field names that were omitted during storage
colnames(cstest) <- c('ID', 'Dollars.Obligated', 'oldagnc', 'country','State', 
                      'Congress.District', 'pop_cd','pop_zip','Agency.Code')

# Filter out non-state juridictions, non-existent district codes
cstest <- filter(cstest, !(str_sub(pop_cd,1,2) %in% c('PR','VI','GU','DC','AS','MP'))) %>%
          filter(., !(pop_cd == 'CA00' | pop_cd == 'WV00')) 

# Select fields needed downstream, and shorten zip to 5 digits (as used in county mapping)
cstest <-select(cstest, ID, Agency.Code, Dollars.Obligated, State, pop_cd, pop_zip)
cstest$Agency.Code <- as.character(cstest$Agency.Code )
cstest$pop_zip <- sapply(cstest$pop_zip, function(x) str_sub(x,1,5))
saveRDS(cstest,"contracts.rds")

rm(cstest)

3. Parsing data on members of congress

The next processing task is to parse the data on committee membership. A key task was producing codes for congressional districts that match those used in the contract data. Additionally, extracting membersโ€™ names will be crucial for joining the two data sources later.

# Get last name (required later for merge)
get.last.name <- function(member_string){
  temp <- str_split(member_string, ",")
  return(temp[[1]][1]) 
}

# Get first name (required later for merge)
get.first.name <- function(member_string){
  temp <- str_split(member_string, ",")
  temp <- temp[[1]][2]
  temp <- str_split(str_sub(temp, start = 2)," ")
  return(temp[[1]][1])
  return(temp)
}

# Get state abbreviation
get.state <- function(member_string){
  temp <- str_split(member_string, " ")
  return(temp[[1]][length(temp[[1]])])
}

# Get district number (0 if from a single-district state such as Delaware)
get.district <- function(member_string){
  temp <- str_split(member_string, " ")
  text <- temp[[1]][length(temp[[1]])-1]
  if(str_detect(text,'[:digit:]+')){
    return(str_extract(text,'[:digit:]+'))
  }else{
    return('0')
  }
}

# Combine state and district number into a 4-character code, e.g. NJ11
get.code <- function(state, district){
  if(str_length(district) == 1)
    return(str_c(state,'0',district))
  else
    return(str_c(state,district))
}

RepData$FirstName <- sapply(RepData$Member, get.first.name)
RepData$LastName <- sapply(RepData$Member, get.last.name)
RepData$State <- sapply(RepData$Member, get.state)
RepData$District <- sapply(RepData$Member, get.district)
RepData$DistrictCode <- mapply(get.code, RepData$State, RepData$District) %>%
                        as.character(.)

RepData <- filter(RepData, !(State %in% c('PR','VI','GU','DC','AS','MP'))) #Filter out non-voting members

The seniority data requires different functions. Note that there are no district numbers in this table.

get.state.senior <- function(ps){
  temp <- str_split(ps,",")
  return(str_sub(temp[[1]][2],2,3))
}

get.last.name.senior <- function(memb){
  temp <- str_split(memb," ")[[1]][-1]
  temp <- ifelse(str_detect(temp,'\\*'),str_sub(temp,1,-2),temp)
  return(temp[[1]])
}

get.first.name.senior <- function(memb){
  temp <- str_split(memb," ")[[1]][1]
  temp <- ifelse(str_detect(temp,'\\*'),str_sub(temp,1,-2),temp)
  return(temp[[1]])
}

SeniorData$FirstName = sapply(SeniorData$Member,get.first.name.senior)
SeniorData$LastName = sapply(SeniorData$Member,get.last.name.senior)
SeniorData$State = sapply(SeniorData$PartyAndState,get.state.senior)

SeniorData <- select(SeniorData, FirstName, LastName, State, Terms)

4. Merging committee data and seniority data

Having parsed committee membership data, the next challenge is to merge committee data with seniority data. Since there's no district data in the seniority table, we need instead to merge by first name, last name, and state.

LeftData <- left_join(RepData, SeniorData, by = c('State','FirstName','LastName'))

Due to features like diacritical marks, abbreviations, and nicknames, the first name/last name/state merge didn't succeed in every case. Since most of the problems seem to be with first names and since matching last names within a state are not common, a good tactic is to take rows that failed to match on the first attempt, attempt a join operation via last name and state, and populate the โ€œTermsโ€ field in the โ€œLeftDataโ€ data frame with successful matches.

MissingLeft <- filter(LeftData,is.na(Terms))
FixerByLast <- left_join(MissingLeft,SeniorData, by = c('State','LastName')) %>%
               select(.,DistrictCode,Terms.y) %>%
               filter(.,!is.na(Terms.y))
for(d in FixerByLast$DistrictCode){
  LeftData$Terms[LeftData$DistrictCode == d] <- FixerByLast$Terms.y[FixerByLast$DistrictCode == d]
}

The same process can be tweaked for the 17 remaining unmatched rows, this time joining on first name and state. (The additional manual correction below is necessary because there are two representatives from NJ named โ€œDonald.โ€)

MissingLeft <- filter(LeftData,is.na(Terms))
FixerByFirst <- left_join(MissingLeft,SeniorData, by = c('State','FirstName')) %>%
  select(.,DistrictCode,Terms.y) %>%
  filter(.,!is.na(Terms.y)) %>%
  filter(., !(DistrictCode=='NJ10' & Terms.y !=3))
for(d in FixerByFirst$DistrictCode){
  LeftData$Terms[LeftData$DistrictCode == d] <- FixerByFirst$Terms.y[FixerByFirst$DistrictCode == d]
}

Having populated โ€œTermsโ€ for the final two unmatched rows manually, all โ€œTermsโ€ can be converted to integers.

LeftData$Terms[LeftData$DistrictCode == 'MO01'] <- 8
LeftData$Terms[LeftData$DistrictCode == 'WA03'] <- 3
LeftData$Terms <- as.integer(LeftData$Terms)

The seniority data in LeftData can now be merged with RepData. We'll additionally want to add a categorical field based on terms. Because of the timing discrepancy noted in the "Processing Data" section earlier, first-term Representatives should get their own category. The remaining categories are to be as close in size to each other as possible.

RepData <- inner_join(RepData, LeftData, by = "DistrictCode") %>%
           select(., ends_with('x'), DistrictCode, Terms) %>%
           select(., Member = Member.x, Committees = Committees.x, State = State.x, DistrictCode, Terms)
RepData$Seniority <- cut(RepData$Terms,
                         c(0,1,3,7,30),
                         c('1st Term', '2 to 3 Terms', '4 to 7 Terms', '8 or More Term'),
                         include.lowest = FALSE)

rm(SeniorData, FixerByFirst, FixerByLast, LeftData, MissingLeft, d, url)
rm(get.code, get.district, 
   get.first.name, get.first.name.senior, 
   get.last.name, get.last.name.senior,
   get.state,
   get.state.senior)

5. Coding committee membership

A useful last preparatory step is to add flags for committees and members with leadership positions.

RepData <- mutate(RepData, Agriculture = str_detect(Committees,'Agriculture')) %>%
           mutate(., Appropriations = str_detect(Committees,'Appropriations')) %>%
           mutate(., ArmedServices = str_detect(Committees,'Armed Services')) %>%
           mutate(., Education = str_detect(Committees,'Education')) %>%
           mutate(., EnergyCommerce = str_detect(Committees,'Energy and')) %>%
           mutate(., HomelandSecurity = str_detect(Committees,'Homeland')) %>%
           mutate(., NaturalResources = str_detect(Committees,'Natural')) %>%
           mutate(., ScienceSpaceTechnology = str_detect(Committees,'Science')) %>%
           mutate(., SmallBusiness = str_detect(Committees,'Small Business')) %>%
           mutate(., Transportation = str_detect(Committees,'Transportation')) %>%
           mutate(., VeteransAffairs = str_detect(Committees,'Veterans')) %>%
           mutate(., Leadership = str_detect(Member,'Boehner.|Pelosi.|McCarthy.|Hoyer.|Clyburn.|Scalise.')) 

write.table(RepData, "CongressData.csv", row.names = FALSE, sep = ',')
saveRDS(RepData,"CongressData.rds")

rm(RepData)

The contract data is now fully prepared to be analyzed. Let's walk through some programming framework and potential avenues for analysis.

Analysis

Set up

First, let's load the data stored during processing, as well as any libraries we'll need.

library(stringr)
library(XML)
library(dplyr,warn.conflicts=FALSE)
library(ggplot2)
library(scales)

contracts <- readRDS("contracts.rds") %>% tbl_df()
agencies <- readRDS("agency_codes.rds") %>% tbl_df()
congress <- readRDS("CongressData.rds") %>% tbl_df()

Analysis 1. Relative impact of agencies

To warm-up, let's display a bar chart showing the largest agencies by contract value. As is widely known, the Defense Department dominates.

library(stringr)
library(dplyr,warn.conflicts=FALSE)
library(ggplot2)
library(scales)

by_agency.plot.data <- inner_join(contracts,agencies, by = c("Agency.Code" = "id")) %>%
                       group_by(.,ShortName) %>%
                       summarise(., Total = sum(Dollars.Obligated)/1e9) %>%
                       filter(., Total > 5)

agency.plot <- ggplot(aes(x=reorder(ShortName,Total), y=Total), data = 
                        by_agency.plot.data) +
               geom_bar(stat = "identity")  +
               scale_x_discrete(name = "") +
               scale_y_continuous(name = "Total Contracts (billions)",
                                  labels = dollar) +
               ggtitle("Largest Agencies by Total Contract Value") +
               theme_bw()

agency.plot

unnamed-chunk-16-1

Analysis 2. Distribution of contract spending across districts

Let's try plotting some histograms featuring congressional districts as data points, bucketing the data according to the total value of contacts in each district.

library(ggplot2)
library(dplyr)
library(scales)

by_district <- group_by(contracts, pop_cd) %>%
               summarise(., Total = sum(Dollars.Obligated)/1e6) %>%
               rename(., DistrictCode = pop_cd) %>%
               semi_join(.,congress, by = "DistrictCode")
by_district$Total <- sapply(by_district$Total, function(x) ifelse(x<1,1,x))

district.plot <- ggplot(aes(x=Total), data = by_district) +
                 geom_histogram() +
                 scale_x_continuous(name = "Total Contracts (millions)",
                     labels = dollar) +
                 ggtitle('Counts of Congressional Districts by Total Contract Values') +
                 ylab('') +
                 theme_bw()

district.plot

unnamed-chunk-17-1

One takeaway from the above plot is that the distribution is highly skewed. We'll therefore have to use log scales in some of our plots. Further statistical analysis might have to employ non-parametric methods.

We can plot similar histograms for specific departments, starting with Defense.

by_district_agency <- inner_join(contracts,agencies, by = c("Agency.Code" = "id")) %>%
                      group_by(., pop_cd, ShortName) %>%
                      summarise(., Total = sum(Dollars.Obligated)/1e6) %>%
                      rename(., DistrictCode = pop_cd) %>%
                      semi_join(.,congress, by = 'DistrictCode')
by_district_agency$Total <- sapply(by_district_agency$Total,  function(x) ifelse(x<1,1,x))

defense.plot <- ggplot(data=filter(by_district_agency,ShortName=='Defense'),
                       aes(x=Total)) +
                geom_histogram(binwidth = 100) +
                scale_x_continuous(name = "Total Contracts (millions)",
                     labels = dollar) +
                ggtitle('Counts of Congressional Districts by Total Defense Contract Values') +
                ylab('') +
                theme_bw()

defense.plot

unnamed-chunk-18-1

To check whether the skew in total spending results purely from the skew in Defense spending, we can make similar plots for other selected departments and agencies.

by_district_agency_other <- filter(by_district_agency, 
                                   ShortName %in% c('NASA', 'Veterans Affairs',
                                                    'HHS', 'Energy'))

other.plot <- ggplot(data = by_district_agency_other, aes(x = Total)) +
              facet_grid(ShortName~.) +
              geom_histogram(binwidth = 10) +
              scale_x_continuous(name = "Total Contracts (millions)",
                                 labels = dollar) +
              ggtitle('Counts of Congressional Districts by Total Contract Values') +
              ylab('') +
              coord_cartesian(xlim = c(0,250)) +
              theme_bw()

other.plot

unnamed-chunk-19-1

It seems the skew in total spending does not result purely from the skew in Defense spending, as skewness is present at multiple scales.

Analysis 3. Spending in districts versus committee membership

Next, let's try plotting some graphs to show the distribution of contract values across congressional districts, according to committee memberships of those Congressperson representing contracted districts. We'll do so by department, showing in each graph the distribution of committees responsible for the given department, as well as the Appropriations committee (responsible for all departments) and all other members of congress.

In order to plot these graphs, we first create a data frame that joins contract data to congressional data, and then a function to explicitly insure uniform-looking plots.

library(ggplot2)
library(dplyr)
library(scales)
by_distr_agc_comm <- inner_join(by_district_agency, congress, by = "DistrictCode") %>%
                     select(., DistrictCode, Seniority, ShortName, Total, 9:20) 


make.plot <- function(DeptName,CommName){
  plot.data <- filter(by_distr_agc_comm, ShortName == DeptName) 
  comm.bool <- select(plot.data,matches(CommName))[[2]]
  plot.data$Committee <- mapply(function(x,y) if(x) CommName 
                                   else if(y) 'Appropriations'
                                   else 'Other',
                                   comm.bool, 
                                   plot.data$Appropriations)
  plot.data$Committee <- factor(plot.data$Committee, 
                                   levels = c(CommName,'Appropriations', 'Leadership','Other'))
  
  return.plot <- ggplot(data = plot.data, 
                        aes(x = Committee, y = Total, color = Committee), guide = TRUE) +
                 geom_jitter(position = position_jitter(height = 0.2, width = 0.25), 
                             size = 2) +
                 coord_trans(y = 'log10') +
                 scale_size_discrete(range = c(2,4)) +
                 scale_y_continuous(name = "Total Contracts (millions)",
                                    labels = dollar) +
                 ggtitle(str_c('Department: ', DeptName)) +
                 scale_x_discrete(labels = '') +
                 geom_hline(yintercept = median(plot.data$Total),
                            color = 'black', linetype = 'solid', width = 2) +
                 xlab('') +
                 theme_bw()
}

Below are the plots for various departments and agencies. The black line represents the median for the set of all 435 districts for the given agency.

Think of these plots as visual contingency tables. For each committee, we can easily check whether more than half the members are above the median line. This is relevant because in a random sample of Representatives we would expect the points in the sample to be split more or less evenly on the two sides of this line.

Likewise, we can visually check whether a given committee is overrepresented among the districts with the most contract spending. (Keep in mind that each committee comprises 10-15% of Congress.)

unnamed-chunk-21-3 unnamed-chunk-21-4 unnamed-chunk-21-5 unnamed-chunk-21-6 unnamed-chunk-21-1 unnamed-chunk-21-2

Analysis 4. Plots by seniority

Since a Representativeโ€™s seniority is a potential contributing factor to spending in his or her district, let's look at plots broken up by seniority buckets. We can also display the size of each bucket for reference.

## 
##       1st Term   2 to 3 Terms   4 to 7 Terms 8 or More Term 
##             59            147            114            115

Something to keep in mind when looking at the plots below is that the leftmost panel displays data for first-term members. These are members who were not involved in the spending decisions. In each case shown, however, more than have the first-term members of the supervising committee are from districts where contract spending is above the overall median.

unnamed-chunk-22-3 unnamed-chunk-22-4 unnamed-chunk-22-5 unnamed-chunk-22-6 unnamed-chunk-22-1 unnamed-chunk-22-2

The pattern we see among the first-term Representatives raises the possibility that the association we observed earlier between contract spending and committee representation results from Representatives being assigned to committees based on the contracts that are already in place in their districts.

Conclusion

These findings are of course preliminary. I did not do an exhaustive analysis of every department/committee, and I have not looked at federal expenditures that are made through grants rather than contracts. These are possible extensions to be made in future projects.

About Author

Stephen Penrice

After starting his career as a Ph.D. in pure mathematics, Stephen has worked continuously to grow his technical proficiency in order to take on more and more challenges with an applied focus. His latest work in the finance...
View all posts by Stephen Penrice >

Leave a Comment

Cancel reply

You must be logged in to post a comment.

No comments found.

View Posts by Categories

All Posts 2399 posts
AI 7 posts
AI Agent 2 posts
AI-based hotel recommendation 1 posts
AIForGood 1 posts
Alumni 60 posts
Animated Maps 1 posts
APIs 41 posts
Artificial Intelligence 2 posts
Artificial Intelligence 2 posts
AWS 13 posts
Banking 1 posts
Big Data 50 posts
Branch Analysis 1 posts
Capstone 206 posts
Career Education 7 posts
CLIP 1 posts
Community 72 posts
Congestion Zone 1 posts
Content Recommendation 1 posts
Cosine SImilarity 1 posts
Data Analysis 5 posts
Data Engineering 1 posts
Data Engineering 3 posts
Data Science 7 posts
Data Science News and Sharing 73 posts
Data Visualization 324 posts
Events 5 posts
Featured 37 posts
Function calling 1 posts
FutureTech 1 posts
Generative AI 5 posts
Hadoop 13 posts
Image Classification 1 posts
Innovation 2 posts
Kmeans Cluster 1 posts
LLM 6 posts
Machine Learning 364 posts
Marketing 1 posts
Meetup 144 posts
MLOPs 1 posts
Model Deployment 1 posts
Nagamas69 1 posts
NLP 1 posts
OpenAI 5 posts
OpenNYC Data 1 posts
pySpark 1 posts
Python 16 posts
Python 458 posts
Python data analysis 4 posts
Python Shiny 2 posts
R 404 posts
R Data Analysis 1 posts
R Shiny 560 posts
R Visualization 445 posts
RAG 1 posts
RoBERTa 1 posts
semantic rearch 2 posts
Spark 17 posts
SQL 1 posts
Streamlit 2 posts
Student Works 1687 posts
Tableau 12 posts
TensorFlow 3 posts
Traffic 1 posts
User Preference Modeling 1 posts
Vector database 2 posts
Web Scraping 483 posts
wukong138 1 posts

Our Recent Popular Posts

AI 4 AI: ChatGPT Unifies My Blog Posts
by Vinod Chugani
Dec 18, 2022
Meet Your Machine Learning Mentors: Kyle Gallatin
by Vivian Zhang
Nov 4, 2020
NICU Admissions and CCHD: Predicting Based on Data Analysis
by Paul Lee, Aron Berke, Bee Kim, Bettina Meier and Ira Villar
Jan 7, 2020

View Posts by Tags

#python #trainwithnycdsa 2019 2020 Revenue 3-points agriculture air quality airbnb airline alcohol Alex Baransky algorithm alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus ames dataset ames housing dataset apartment rent API Application artist aws bank loans beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Best Data Science Bootcamp 2020 Best Ranked Big Data Book Launch Book-Signing bootcamp Bootcamp Alumni Bootcamp Prep boston safety Bundles cake recipe California Cancer Research capstone car price Career Career Day ChatGPT citibike classic cars classpass clustering Coding Course Demo Course Report covid 19 credit credit card crime frequency crops D3.js data data analysis Data Analyst data analytics data for tripadvisor reviews data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization database Deep Learning Demo Day Discount disney dplyr drug data e-commerce economy employee employee burnout employer networking environment feature engineering Finance Financial Data Science fitness studio Flask flight delay football gbm Get Hired ggplot2 googleVis H20 Hadoop hallmark holiday movie happiness healthcare frauds higgs boson Hiring hiring partner events Hiring Partners hotels housing housing data housing predictions housing price hy-vee Income industry Industry Experts Injuries Instructor Blog Instructor Interview insurance italki Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter las vegas airport lasso regression Lead Data Scienctist Lead Data Scientist leaflet league linear regression Logistic Regression machine learning Maps market matplotlib Medical Research Meet the team meetup methal health miami beach movie music Napoli NBA netflix Networking neural network Neural networks New Courses NHL nlp NYC NYC Data Science nyc data science academy NYC Open Data nyc property NYCDSA NYCDSA Alumni Online Online Bootcamp Online Training Open Data painter pandas Part-time performance phoenix pollutants Portfolio Development precision measurement prediction Prework Programming public safety PwC python Python Data Analysis python machine learning python scrapy python web scraping python webscraping Python Workshop R R Data Analysis R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest Ranking recommendation recommendation system regression Remote remote data science bootcamp Scrapy scrapy visualization seaborn seafood type Selenium sentiment analysis sentiment classification Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau teachers team team performance TensorFlow Testimonial tf-idf Top Data Science Bootcamp Top manufacturing companies Transfers tweets twitter videos visualization wallstreet wallstreetbets web scraping Weekend Course What to expect whiskey whiskeyadvocate wildfire word cloud word2vec XGBoost yelp youtube trending ZORI

NYC Data Science Academy

NYC Data Science Academy teaches data science, trains companies and their employees to better profit from data, excels at big data project consulting, and connects trained Data Scientists to our industry.

NYC Data Science Academy is licensed by New York State Education Department.

Get detailed curriculum information about our
amazing bootcamp!

Please enter a valid email address
Sign up completed. Thank you!

Offerings

  • HOME
  • DATA SCIENCE BOOTCAMP
  • ONLINE DATA SCIENCE BOOTCAMP
  • Professional Development Courses
  • CORPORATE OFFERINGS
  • HIRING PARTNERS
  • About

  • About Us
  • Alumni
  • Blog
  • FAQ
  • Contact Us
  • Refund Policy
  • Join Us
  • SOCIAL MEDIA

    ยฉ 2025 NYC Data Science Academy
    All rights reserved. | Site Map
    Privacy Policy | Terms of Service
    Bootcamp Application