使用 tabulizer 包基于字符串提取列表

Extract list based on string with tabulizer package

使用 tabulizer 包提取季度损益表并将其转换为表格形式。

# 2017 Q3 Report
telia_url = "http://www.teliacompany.com/globalassets/telia-
company/documents/reports/2017/q3/telia-company-q3-2017-en"
telialists = extract_tables(telia_url)
teliatest1 = as.data.frame(telialists[22])

#2009 Q3#
telia_url2009 = "http://www.teliacompany.com/globalassets/telia-
company/documents/reports/2009/q3/teliasonera-q3-2009-report-en.pdf"
telialists2009 = extract_tables(telia_url2009)
teliatest2 = as.data.frame(telialists2009[9])

仅对简明综合收益表table感兴趣。此字符串与所有历史报告完全相同或非常相似。

以上,对于 2017 年的报告,列表 #22 是正确的 table。但是,由于 2009 年的报告有不同的布局,#9 是该特定报告的正确格式。

根据 "Condensed Consolidated Statements of Comprehensive Income" 的字符串(或子字符串)所在的位置,使此函数动态化的聪明解决方案是什么?

也许使用 tm 包来查找相对位置?

谢谢

您可以使用 pdftools 找到您感兴趣的页面。

例如,像这样的函数应该可以完成这项工作:

get_table <- function(url) {
  txt <- pdftools::pdf_text(url)
  p <- grep("condensed consolidated statements.{0,10}comprehensive income", 
            txt,
            ignore.case = TRUE)[1]
  L <- tabulizer::extract_tables(url, pages = p)
  i <- which.max(lengths(L))
  data.frame(L[[i]])
}

第一步是读取字符向量txt中的所有页面。然后 grep 允许您找到看起来像您想要的第一页(我插入 .{0,10} 以允许标题中间最多十个字符,如空格或换行符)。

使用tabulizer,您可以提取位于这个页面上的所有table的列表L,这应该会快得多而不是像您那样提取文档的所有 table。您的 table 可能是该页面上最大的,因此 which.max.