Setup

Load Packages

library( irs990efile )  # functions for parsing efile XMLs
library( dplyr )        # data wrangling
library( purrr )        # data wrangling 
library( pander )       # formatting
library( knitr )        # formatting
library( DT )           # table printing
library( httr )         # web requests 
library( xmltools )     # xml utilities
library( xml2 )         # xml utilities
library( XML )          # xml utilities 
library( data.tree )    # network visualization
library( networkD3 )    # network visualization
library( igraph )       # network visualization

source( "R/rdb-functions-v2.R")
source( "R/utils.R")

Data

head( index )

The Concordance File

The concordance is an RDB to XML Crosswalk that maps all xpaths onto a specified set of variables. It is located in the irs990efile package.


The full data dictionary is available on GitHub.

DATA DICTIONARY


concordance %>% 
  filter( rdb_table == table.name )  








xpath id
/Return/ReturnData/IRS990/Form990PartIX/OtherExpenses/Description 1
/Return/ReturnData/IRS990/Form990PartIX/OtherExpenses/Fundraising 2
/Return/ReturnData/IRS990/Form990PartIX/OtherExpenses/ManagementAndGeneral 3
/Return/ReturnData/IRS990/Form990PartIX/OtherExpenses/ProgramServices 4
/Return/ReturnData/IRS990/Form990PartIX/OtherExpenses/Total 5
/Return/ReturnData/IRS990/OtherExpenses/Description 6
/Return/ReturnData/IRS990/OtherExpenses/Fundraising 7
/Return/ReturnData/IRS990/OtherExpenses/ManagementAndGeneral 8
/Return/ReturnData/IRS990/OtherExpenses/ProgramServices 9
/Return/ReturnData/IRS990/OtherExpenses/Total 10
/Return/ReturnData/IRS990/OtherExpensesGrp/Desc 11
/Return/ReturnData/IRS990/OtherExpensesGrp/FundraisingAmt 12
/Return/ReturnData/IRS990/OtherExpensesGrp/ManagementAndGeneralAmt 13
/Return/ReturnData/IRS990/OtherExpensesGrp/ProgramServicesAmt 14
/Return/ReturnData/IRS990/OtherExpensesGrp/TotalAmt 15
xpaths <- as.character( t.xpaths$xpath )
el <- create_edgelist_v1( xpaths )
nd <- FromDataFrameNetwork( network=el )
print( nd )
##                                   levelName
## 1  Return                                  
## 2   °--ReturnData                          
## 3       °--IRS990                          
## 4           ¦--Form990PartIX               
## 5           ¦   °--OtherExpenses           
## 6           ¦       ¦--Description         
## 7           ¦       ¦--Fundraising         
## 8           ¦       ¦--ManagementAndGeneral
## 9           ¦       ¦--ProgramServices     
## 10          ¦       °--Total               
## 11          ¦--OtherExpenses               
## 12          ¦   ¦--Description             
## 13          ¦   ¦--Fundraising             
## 14          ¦   ¦--ManagementAndGeneral    
## 15          ¦   ¦--ProgramServices         
## 16          ¦   °--Total                   
## 17          °--OtherExpensesGrp            
## 18              ¦--Desc                    
## 19              ¦--FundraisingAmt          
## 20              ¦--ManagementAndGeneralAmt 
## 21              ¦--ProgramServicesAmt      
## 22              °--TotalAmt
SetGraphStyle( nd, rankdir = "LR")
SetEdgeStyle( nd, arrowhead = "vee", color = "grey20", penwidth = 2 )
SetNodeStyle( nd, 
              style = "filled,rounded", 
              shape = "box", 
              fillcolor = "LightBlue", 
              fontname = "helvetica", 
              fontcolor="black",
              tooltip = GetDefaultTooltip )

# SetNodeStyle(acme$IT, fillcolor = "LightBlue", penwidth = "5px")
plot( nd )
# old version
find_group_names( table.name )
## [1] "//Form990PartIX"    "//OtherExpenses"    "//OtherExpensesGrp"
# new version
find_table_headers( table.name )
##  [1] "//Form990PartIX/GrantsToDomesticOrgs"          
##  [2] "//Form990PartIX/GrantsToDomesticIndividuals"   
##  [3] "//Form990PartIX/ForeignGrants"                 
##  [4] "//Form990PartIX/BenefitsToMembers"             
##  [5] "//Form990PartIX/CompCurrentOfficersDirectors"  
##  [6] "//Form990PartIX/CompDisqualPersons"            
##  [7] "//Form990PartIX/OtherSalariesAndWages"         
##  [8] "//Form990PartIX/PensionPlanContributions"      
##  [9] "//Form990PartIX/OtherEmployeeBenefits"         
## [10] "//Form990PartIX/PayrollTaxes"                  
## [11] "//Form990PartIX/FeesForServicesManagement"     
## [12] "//Form990PartIX/FeesForServicesLegal"          
## [13] "//Form990PartIX/FeesForServicesAccounting"     
## [14] "//Form990PartIX/FeesForServicesLobbying"       
## [15] "//Form990PartIX/FeesForServicesProfFundraising"
## [16] "//Form990PartIX/FeesForServicesInvstMgmntFees" 
## [17] "//Form990PartIX/FeesForServicesOther"          
## [18] "//Form990PartIX/Advertising"                   
## [19] "//Form990PartIX/OfficeExpenses"                
## [20] "//Form990PartIX/InformationTechnology"         
## [21] "//Form990PartIX/Royalties"                     
## [22] "//Form990PartIX/Occupancy"                     
## [23] "//Form990PartIX/Travel"                        
## [24] "//Form990PartIX/TravelEntrtnmntPublicOfficials"
## [25] "//Form990PartIX/ConferencesMeetings"           
## [26] "//Form990PartIX/Interest"                      
## [27] "//Form990PartIX/PaymentsToAffiliates"          
## [28] "//Form990PartIX/DepreciationDepletion"         
## [29] "//Form990PartIX/Insurance"                     
## [30] "//Form990PartIX/OtherExpenses"                 
## [31] "//Form990PartIX/AllOtherExpenses"              
## [32] "//Form990PartIX/TotalFunctionalExpenses"       
## [33] "//Form990PartIX/JointCosts"                    
## [34] "//Form990PartIX/TotalJointCosts"               
## [35] "//OtherExpenses/OtherExpenses"                 
## [36] "//OtherExpenses/Form990PartIX"                 
## [37] "//OtherExpenses/AllOtherExpenses"              
## [38] "//OtherExpensesGrp/IRS990"                     
## [39] "//OtherExpensesGrp/IRS990ScheduleA"
# manual
if( ! is.null(table.headers) )
{table.headers}
## [1] "//IRS990/Form990PartIX/OtherExpenses"
## [2] "//IRS990/OtherExpenses"              
## [3] "//IRS990/OtherExpensesGrp"








Build the Table

# create new folder
dir.create( folder.name )
setwd( folder.name )

# create sample
set.seed( 1234 )
sample.index <- sample_n( index, sample.size )
write.csv( index, "sample-index.csv", row.names=F )
sample.urls <- sample.index$URL

# erase existing log files
file.create("XPATH-LOG.txt") 
file.create("FAIL-LOG.txt")


start.build.time <- Sys.time()    # --------------------

results.list <- list()
xpath.list <- list()


for( i in 1:length( sample.urls ) )
{
  
  url <- sample.urls[i]
  
  results.list[[i]] <- 
    build_rdb_table_v2( url, 
                        table.name, 
                        table.headers=table.headers )
  
  xpath.list[[i]]   <- 
    get_table_xpaths( url, 
                      table.name, 
                      table.headers=table.headers )
  
  if( i %% 100 == 0 ){ print(i) }
  
}


end.build.time <- Sys.time()      # --------------------


df <- dplyr::bind_rows( results.list )


fail.log <- readLines( "FAIL-LOG.txt" )
all.xpaths <- xpath.list %>% unlist() %>% unique() %>% sort()
cat( all.xpaths, sep="\n", file="XPATH-LOG.txt" )

TABLE: F9-P09-T01-EXPENSES-OTHER

## [1] "NUMBER OF RETURNS PROCESSED:   1000"
## [1] "TOTAL NUMBER OF TABLE ROWS:   2130"

TOTAL RUN TIME:

## Time difference of 16.79673 mins
## Time difference of -0.2799455 hours

Write to File

write.csv( df, paste0( folder.name, "/", table.name, ".csv" ), row.names=F )
head(df) 

Are all names standardized?

names(df)
##  [1] "OBJECT_ID"           "EIN"                 "NAME"               
##  [4] "TAXYR"               "FORMTYPE"            "URL"                
##  [7] "F9_09_EXP_OTH_TOT"   "F9_09_EXP_OTH_DESC"  "F9_09_EXP_OTH_PROG" 
## [10] "F9_09_EXP_OTH_MGMT"  "F9_09_EXP_OTH_FUNDR"








Diagnostics

Missing or Extra XPATHS

Check for xpaths that were used in the tables but do not exist in the Concordance file.

c.table <- dplyr::filter( concordance, rdb_table == table.name ) 
xpath.concordance <- c.table$xpath
setdiff( all.xpaths, xpath.concordance )
## [1] ""                                          
## [2] "/Return/ReturnData/IRS990/OtherExpenses"   
## [3] "/Return/ReturnData/IRS990/OtherExpensesGrp"

Capture to update the Concordance file.

these <- setdiff( all.xpaths, xpath.concordance )
cat( these, sep="\n", file=paste0( folder.name, "/MISSING-XPATHS.txt" ) )

Failes URLs

Check the status of failed URLs.

if( length(fail.log) > 0 )
{ 
  sapply( fail.log, get_message ) %>% 
  table() %>% 
  pander() 
} else {
  print("ALL URLs ARE VALID")
}
Client error: (404) Not Found
1








XML Table Structure

Create Network Edgelists

The create_edgelist() functions v1 and v2 are in R/utils.R.

V1 retains the root nodes Return and ReturnData.

V2 drops the root nodes and uses form versions “990” and “990EZ” as the root to visualize the sets of tables separately.

# KEEP ROOT NOTES Return & ReturnData
el <- create_edgelist_v1( all.xpaths )



Edgelist format:

V1 V2
Return ReturnData
ReturnData IRS990
IRS990 Form990PartVIISectionAGrp
Form990PartVIISectionAGrp PersonNm
Form990PartVIISectionAGrp TitleTxt
Form990PartVIISectionAGrp AverageHoursPerWeekRt
Form990PartVIISectionAGrp IndividualTrusteeOrDirectorInd
Form990PartVIISectionAGrp OfficerInd
Form990PartVIISectionAGrp ReportableCompFromOrgAmt
Form990PartVIISectionAGrp ReportableCompFromRltdOrgAmt








Visualize Tree Structure

# library( data.tree )
nd <- FromDataFrameNetwork( network=el )
print( nd )
##                                  levelName
## 1  Return                                 
## 2   °--ReturnData                         
## 3       °--IRS990                         
## 4           ¦--OtherExpenses              
## 5           ¦   ¦--Description            
## 6           ¦   ¦--Fundraising            
## 7           ¦   ¦--ManagementAndGeneral   
## 8           ¦   ¦--ProgramServices        
## 9           ¦   °--Total                  
## 10          °--OtherExpensesGrp           
## 11              ¦--Desc                   
## 12              ¦--FundraisingAmt         
## 13              ¦--ManagementAndGeneralAmt
## 14              ¦--ProgramServicesAmt     
## 15              °--TotalAmt
SetGraphStyle( nd, rankdir = "LR")
SetEdgeStyle( nd, arrowhead = "vee", color = "grey20", penwidth = 2 )
SetNodeStyle( nd, 
              style = "filled,rounded", 
              shape = "box", 
              fillcolor = "LightBlue", 
              fontname = "helvetica", 
              fontcolor="black",
              tooltip = GetDefaultTooltip )

# SetNodeStyle(acme$IT, fillcolor = "LightBlue", penwidth = "5px")
plot( nd )
# library( networkD3 )
# net <- ToDataFrameNetwork( nd, "name" )
# simpleNetwork( net, fontSize = 12 )
simpleNetwork( el, fontSize = 12 )
#plot with networkD3
radnet <- ToListExplicit( nd, unname = TRUE )
radialNetwork( radnet, fontSize = 12 )








XPATH Summary

Unique Xpaths for this RDB Table

t.xpaths <- 
  concordance %>%
  filter( rdb_table == table.name ) %>% 
  select( xpath ) %>% 
  unique() %>% 
  arrange( xpath ) %>% 
  mutate( id=row_number() ) 

t.xpaths %>% 
  kable( align="l" )
xpath id
/Return/ReturnData/IRS990/Form990PartIX/OtherExpenses/Description 1
/Return/ReturnData/IRS990/Form990PartIX/OtherExpenses/Fundraising 2
/Return/ReturnData/IRS990/Form990PartIX/OtherExpenses/ManagementAndGeneral 3
/Return/ReturnData/IRS990/Form990PartIX/OtherExpenses/ProgramServices 4
/Return/ReturnData/IRS990/Form990PartIX/OtherExpenses/Total 5
/Return/ReturnData/IRS990/OtherExpenses/Description 6
/Return/ReturnData/IRS990/OtherExpenses/Fundraising 7
/Return/ReturnData/IRS990/OtherExpenses/ManagementAndGeneral 8
/Return/ReturnData/IRS990/OtherExpenses/ProgramServices 9
/Return/ReturnData/IRS990/OtherExpenses/Total 10
/Return/ReturnData/IRS990/OtherExpensesGrp/Desc 11
/Return/ReturnData/IRS990/OtherExpensesGrp/FundraisingAmt 12
/Return/ReturnData/IRS990/OtherExpensesGrp/ManagementAndGeneralAmt 13
/Return/ReturnData/IRS990/OtherExpensesGrp/ProgramServicesAmt 14
/Return/ReturnData/IRS990/OtherExpensesGrp/TotalAmt 15

Grouping Variables

Identify all unique groups used in xpaths.

if( is.null(table.headers) )
{ find_table_headers( table.name ) } else
table.headers
## [1] "//IRS990/Form990PartIX/OtherExpenses"
## [2] "//IRS990/OtherExpenses"              
## [3] "//IRS990/OtherExpensesGrp"

Groups can then be used to extract the 1:M RDB tables:

if( is.null(table.headers) )
{ table.headers <- find_table_headers( table.name ) }
demo.url <- "https://nccs-efile.s3.us-east-1.amazonaws.com/xml/201913079349300206_public.xml"
doc <- xml2::read_xml( demo.url )
xml2::xml_ns_strip( doc )
df.demo <- get_table_v2( doc, table.name, table.headers )
df.demo 
## # A tibble: 4 × 1
##   TotalAmt
##   <chr>   
## 1 814     
## 2 53320   
## 3 61281   
## 4 439

Standardize Variable Names

Mapping of xml variable names to concordance variable names:

get_var_map( table.name=table.name )

A table with proper names:

v.map <- get_var_map( table.name=table.name )

if( ! is.null(df.demo) )
{re_name( df.demo, v.map ) %>% as.data.frame()}
##   F9_09_EXP_OTH_TOT
## 1               814
## 2             53320
## 3             61281
## 4               439