I am trying to scrape this PDF containing information about company subsidiaries. I have seen many posts using the R package Tabulizer but this, unfortunately, doesn't work on my Mac for some reasons. As Tabulizer uses Java dependencies, I tried installing different versions of Java (6-13) and then reinstalling the packages, still no luck in getting this to work (what happens is when I run extract_tables
the R session aborts).
I need to scrape the whole pdf from page 19 onwards and construct a table showing company names and their subsidiaries. In the pdf, names start with any letters/number/symbol, whereas subsidiaries start with either a single or double dot.
So I tried with pdftools
and pdftables
packages. The code below provides a table similar to the one on page 19:
library(pdftools)
library(pdftables)
library(tidyverse)
tt = pdf_text("~/DATA/978-1-912036-41-7-Who Owns Whom UK-Ireland-Volume-1.pdf")
df <- tt[19]
df2 <- strsplit(df, ' ')
df3 <-as.data.frame(do.call(cbind, df2)) %>%
filter(V1!="") %>%
mutate(V2=str_split_fixed(V1, "England . ", 2)) %>%
mutate(V3=str_split_fixed(V1, "England", 2)) %>%
select(V2,V3,V1) %>%
mutate(V1=ifelse(V1==V3,"",V1),V3=ifelse(V3==V2,"",V3)) %>%
select(V3,V2,V1) %>%
mutate_at(c("V1"), funs(lead), n = 1 ) %>%
mutate_at(c("V3"), funs(lag), n = 1 ) %>%
unite(V4,V1, V2, V3, sep = "", remove = FALSE)
I am sure there is a more sophisticated function to do this more neatly. For example by using '\n'
or '\r'
with strsplit
:
df2 <- strsplit(df, '\n')
df3 <- do.call(cbind.data.frame, df2)
Can anyone with more experience than me advise me on how to scrape this table?
Like @Justin Coco hinted, this was a lot of fun. The code ended up a bit more complex than I anticipated, but I think the result should be what you imagined.
I used
pdf_data
instead ofpdf_text
so I can work with the position of words.I then wrote a function which can process a page from the PDF:
You can test this on one page or loop through all of them at once:
I already like the df, but you requested that the table should be "showing company names and their subsidiaries". So let's do some more wrangling on the
pdf_df
object.Created on 2021-05-23 by the reprex package (v2.0.0)
Let me know in a comment if there are problems. I obviously didn't go through all pages to check if the script has some quirks with specific company names etc. but the first pages look fine to me.