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/IRS990ScheduleA/Form990ScheduleAPartI/SumOfAmounts 1
/Return/ReturnData/IRS990ScheduleA/Form990ScheduleAPartI/SupportedOrgInformation/Amount 2
/Return/ReturnData/IRS990ScheduleA/Form990ScheduleAPartI/SupportedOrgInformation/EIN 3
/Return/ReturnData/IRS990ScheduleA/Form990ScheduleAPartI/SupportedOrgInformation/ListedInGoverningDoc 4
/Return/ReturnData/IRS990ScheduleA/Form990ScheduleAPartI/SupportedOrgInformation/Name/BusinessNameLine1 5
/Return/ReturnData/IRS990ScheduleA/Form990ScheduleAPartI/SupportedOrgInformation/Name/BusinessNameLine2 6
/Return/ReturnData/IRS990ScheduleA/Form990ScheduleAPartI/SupportedOrgInformation/TypeOfOrganization 7
/Return/ReturnData/IRS990ScheduleA/OtherSupportSumAmt 8
/Return/ReturnData/IRS990ScheduleA/SumOfAmounts 9
/Return/ReturnData/IRS990ScheduleA/SupportSumAmt 10
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformation/Amount 11
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformation/EIN 12
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformation/ListedInGoverningDoc 13
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformation/Name/BusinessNameLine1 14
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformation/Name/BusinessNameLine2 15
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformation/TypeOfOrganization 16
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/EIN 17
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/GoverningDocumentListedInd 18
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/OrganizationTypeCd 19
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/OrganizationTypeDesc 20
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/OtherSupportAmt 21
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/SupportAmt 22
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/SupportedOrganizationName/BusinessNameLine1 23
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/SupportedOrganizationName/BusinessNameLine1Txt 24
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/SupportedOrganizationName/BusinessNameLine2 25
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/SupportedOrganizationName/BusinessNameLine2Txt 26
xpaths <- as.character( t.xpaths$xpath )
el <- create_edgelist_v1( xpaths )
nd <- FromDataFrameNetwork( network=el )
print( nd )
##                                     levelName
## 1  Return                                    
## 2   °--ReturnData                            
## 3       °--IRS990ScheduleA                   
## 4           ¦--Form990ScheduleAPartI         
## 5           ¦   ¦--SumOfAmounts              
## 6           ¦   °--SupportedOrgInformation   
## 7           ¦       ¦--Amount                
## 8           ¦       ¦--EIN                   
## 9           ¦       ¦--ListedInGoverningDoc  
## 10          ¦       ¦--Name                  
## 11          ¦       ¦   ¦--BusinessNameLine1 
## 12          ¦       ¦   °--BusinessNameLine2 
## 13          ¦       °--TypeOfOrganization    
## 14          ¦--OtherSupportSumAmt            
## 15          ¦--SumOfAmounts                  
## 16          ¦--SupportSumAmt                 
## 17          ¦--SupportedOrgInformation       
## 18          ¦   ¦--Amount                    
## 19          ¦   ¦--EIN                       
## 20          ¦   ¦--ListedInGoverningDoc      
## 21          ¦   ¦--Name                      
## 22          ¦   ¦   ¦--BusinessNameLine1     
## 23          ¦   ¦   °--BusinessNameLine2     
## 24          ¦   °--TypeOfOrganization        
## 25          °--SupportedOrgInformationGrp    
## 26              ¦--EIN                       
## 27              ¦--GoverningDocumentListedInd
## 28              ¦--OrganizationTypeCd        
## 29              ¦--OrganizationTypeDesc      
## 30              ¦--OtherSupportAmt           
## 31              ¦--SupportAmt                
## 32              °--SupportedOrganizationName 
## 33                  ¦--BusinessNameLine1     
## 34                  ¦--BusinessNameLine1Txt  
## 35                  ¦--BusinessNameLine2     
## 36                  °--BusinessNameLine2Txt
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] "//Form990ScheduleAPartI"      "//SupportedOrgInformation"   
## [3] "//SupportedOrgInformationGrp" "//OtherSupportSumAmt"        
## [5] "//SumOfAmounts"               "//SupportSumAmt"
# new version
find_table_headers( table.name )
##  [1] "//Form990ScheduleAPartI/Church170b1Ai"                  
##  [2] "//Form990ScheduleAPartI/School170b1Aii"                 
##  [3] "//Form990ScheduleAPartI/Hospital170b1Aiii"              
##  [4] "//Form990ScheduleAPartI/HospitalNameAndAddress"         
##  [5] "//Form990ScheduleAPartI/MedicalResearchOrg170b1Aiii"    
##  [6] "//Form990ScheduleAPartI/CollegeSupportOrg170b1Aiv"      
##  [7] "//Form990ScheduleAPartI/GovernmentalUnit170b1Av"        
##  [8] "//Form990ScheduleAPartI/PubliclySupportedOrg170b1Avi"   
##  [9] "//Form990ScheduleAPartI/CommunityTrust170b1Avi"         
## [10] "//Form990ScheduleAPartI/PubliclySupportedOrg509a2"      
## [11] "//Form990ScheduleAPartI/TestingForPublicSafety509a4"    
## [12] "//Form990ScheduleAPartI/SupportingOrganization509a3"    
## [13] "//Form990ScheduleAPartI/SupportingOrg509a3Type1"        
## [14] "//Form990ScheduleAPartI/SupportingOrg509a3Type2"        
## [15] "//Form990ScheduleAPartI/SupportingOrg509a3Type3FuncInt" 
## [16] "//Form990ScheduleAPartI/WrittenIRSDetermination"        
## [17] "//Form990ScheduleAPartI/SupportedOrgInformation"        
## [18] "//Form990ScheduleAPartI/SumOfAmounts"                   
## [19] "//Form990ScheduleAPartI/SupportingOrg509a3Type3Other"   
## [20] "//Form990ScheduleAPartI/CertificationCheckbox"          
## [21] "//Form990ScheduleAPartI/ContribByControllingIndividual" 
## [22] "//Form990ScheduleAPartI/ContributionByRelatedParty"     
## [23] "//Form990ScheduleAPartI/ContribBy35ControlledEntity"    
## [24] "//SupportedOrgInformation/Form990ScheduleAPartI"        
## [25] "//SupportedOrgInformation/SupportedOrgInformation"      
## [26] "//SupportedOrgInformationGrp/SupportedOrganizationName" 
## [27] "//SupportedOrgInformationGrp/EIN"                       
## [28] "//SupportedOrgInformationGrp/OrganizationTypeCd"        
## [29] "//SupportedOrgInformationGrp/OrganizationTypeDesc"      
## [30] "//SupportedOrgInformationGrp/GoverningDocumentListedInd"
## [31] "//SupportedOrgInformationGrp/SupportAmt"                
## [32] "//SupportedOrgInformationGrp/OtherSupportAmt"           
## [33] "//SupportedOrgInformationGrp/SupportedOrgNotifiedInd"   
## [34] "//SupportedOrgInformationGrp/USOrganizedInd"            
## [35] "//OtherSupportSumAmt/"                                  
## [36] "//SumOfAmounts/"                                        
## [37] "//SupportSumAmt/"
# manual
if( ! is.null(table.headers) )
{table.headers}
## [1] "//IRS990ScheduleA/Form990ScheduleAPartI"     
## [2] "//IRS990ScheduleA/SupportedOrgInformation"   
## [3] "//IRS990ScheduleA/SupportedOrgInformationGrp"








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: SA-P01-T01-PUBLIC-CHARITY-STATUS

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

TOTAL RUN TIME:

## Time difference of 12.75047 mins
## Time difference of -0.2125079 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"                          
##  [3] "NAME"                          "TAXYR"                        
##  [5] "FORMTYPE"                      "URL"                          
##  [7] "SA_01_PCSTAT_ORG_EIN"          "SA_01_PCSTAT_ORG_TYPE"        
##  [9] "SA_01_PCSTAT_ORG_DOC_LISTED_X" "SA_01_PCSTAT_ORG_AMT_SUPPORT" 
## [11] "SA_01_PCSTAT_ORG_AMT_OTH"      "SA_01_PCSTAT_ORG_NAME_L1"     
## [13] "SA_01_PCSTAT_ORG_NAME_L2"








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/IRS990ScheduleA/SupportedOrgInformationGrp"                          
## [3] "/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/SupportedOrganizationName"

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")
}
## [1] "ALL URLs ARE VALID"








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       °--IRS990ScheduleA                   
## 4           °--SupportedOrgInformationGrp    
## 5               ¦--EIN                       
## 6               ¦--GoverningDocumentListedInd
## 7               ¦--OrganizationTypeCd        
## 8               ¦--OtherSupportAmt           
## 9               ¦--SupportAmt                
## 10              °--SupportedOrganizationName 
## 11                  ¦--BusinessNameLine1Txt  
## 12                  °--BusinessNameLine2Txt
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/IRS990ScheduleA/Form990ScheduleAPartI/SumOfAmounts 1
/Return/ReturnData/IRS990ScheduleA/Form990ScheduleAPartI/SupportedOrgInformation/Amount 2
/Return/ReturnData/IRS990ScheduleA/Form990ScheduleAPartI/SupportedOrgInformation/EIN 3
/Return/ReturnData/IRS990ScheduleA/Form990ScheduleAPartI/SupportedOrgInformation/ListedInGoverningDoc 4
/Return/ReturnData/IRS990ScheduleA/Form990ScheduleAPartI/SupportedOrgInformation/Name/BusinessNameLine1 5
/Return/ReturnData/IRS990ScheduleA/Form990ScheduleAPartI/SupportedOrgInformation/Name/BusinessNameLine2 6
/Return/ReturnData/IRS990ScheduleA/Form990ScheduleAPartI/SupportedOrgInformation/TypeOfOrganization 7
/Return/ReturnData/IRS990ScheduleA/OtherSupportSumAmt 8
/Return/ReturnData/IRS990ScheduleA/SumOfAmounts 9
/Return/ReturnData/IRS990ScheduleA/SupportSumAmt 10
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformation/Amount 11
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformation/EIN 12
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformation/ListedInGoverningDoc 13
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformation/Name/BusinessNameLine1 14
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformation/Name/BusinessNameLine2 15
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformation/TypeOfOrganization 16
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/EIN 17
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/GoverningDocumentListedInd 18
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/OrganizationTypeCd 19
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/OrganizationTypeDesc 20
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/OtherSupportAmt 21
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/SupportAmt 22
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/SupportedOrganizationName/BusinessNameLine1 23
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/SupportedOrganizationName/BusinessNameLine1Txt 24
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/SupportedOrganizationName/BusinessNameLine2 25
/Return/ReturnData/IRS990ScheduleA/SupportedOrgInformationGrp/SupportedOrganizationName/BusinessNameLine2Txt 26

Grouping Variables

Identify all unique groups used in xpaths.

if( is.null(table.headers) )
{ find_table_headers( table.name ) } else
table.headers
## [1] "//IRS990ScheduleA/Form990ScheduleAPartI"     
## [2] "//IRS990ScheduleA/SupportedOrgInformation"   
## [3] "//IRS990ScheduleA/SupportedOrgInformationGrp"

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 
## NULL

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()}