将不规则和混合的 ASCII 文件读取并解析为 R

Read and parse an irregular and mixed ASCII file into R

我对 R 还是很陌生,如果我没有使用正确的术语,我深表歉意。我有兴趣从 Treasury Direct 在线报告查询系统 (http://www.treasurydirect.gov/govt/reports/tfmp/tfmp_utf.htm) 中提取大量失业保险信托基金数据,并且我已经使用 readLines 成功提取了信息。

ESAA_OCT15 <- readLines('http://www.treasurydirect.gov/govt/reports/tfmp/utf/es/dfiw01015tses.txt')

这给了我图表作为字符串向量。

有没有一种方法可以解析这些行并将其转换为数据框,这样我至少可以将它 excel 并轻松地从中获取重要信息?我敢肯定还有另一种方法可以做到这一点,但报告在包含哪些会计代码部分以及包含多少个人交易方面总是会有所不同,所以我什至不确定从哪里开始。

我需要的项目是日期、share/par(美元交易金额)、交易代码和交易描述。总数会很有用,但绝不是必需的。

当你使用 Excel 查看它时,它看起来像

这将帮助您解析信息:

ESAA_OCT15 <- readLines('http://www.treasurydirect.gov/govt/reports/tfmp/utf/es/dfiw01015tses.txt')
# Select lines with /
z = grepl(pattern = "/",x = ESAA_OCT15)
d = trimws(ESAA_OCT15[z])

dates = substr(d,0,10)
sharesPar = substr(d,11,41)

这是首先 select 所有包含 / 字符的行。这甚至 return 列标题。这些存储在 d.

如果你检查 d:

[1] "Effective Date                 Shares/Par  Description Code           Memo Number    Code      Account Number"
 [2] "10/01/2015                 2,313,000.0000  12-10 FUTA RECEIPTS         3305617                 ESAA"          
 [3] "10/01/2015                 3,663,000.0000  12-10 FUTA RECEIPTS         3305618                 ESAA"          
 [4] "10/02/2015                 4,314,000.0000  12-10 FUTA RECEIPTS         3305640                 ESAA"          
 [5] "10/05/2015                 3,512,000.0000  12-10 FUTA RECEIPTS         3305662                 ESAA"

信息排列整齐。这意味着每一列的数据都在一个精确的位置结束。要解析它,您可以使用 substr 启动和停止,如我的脚本所示。

当然,我没有完成所有的解析,我会让你完成剩下的。解析每一列后,创建一个 data.frame(dates, sharesPar, ...)

这是一个固定宽度的格式,所以应该这样处理:

library(dplyr)
library(readr)

readLines("http://www.treasurydirect.gov/govt/reports/tfmp/utf/es/dfiw01015tses.txt") %>% 
  grep("^\ +[[:digit:]]+/[[:digit:]]+", ., value=TRUE) %>% # grab only the lines with data
  textConnection() %>% 
read.fwf(widths=c(19, 26, 27, 15, 10, 27), skip=7) %>%     # read the columns
  mutate_all(trimws) %>%                                   # clean them up
  type_convert() %>%                                       # you still need to convert the date even with this type conversion
  setNames(c("effective_date", "shares_per",               # add decent colnames
             "trans_descr_code", "memo_num", "location_code", "acct_no"))