【问题标题】:fread does not read character vectorfread 不读取字符向量
【发布时间】:2019-03-31 06:53:49
【问题描述】:

我正在尝试使用带有以下代码的 R 下载列表:

name <- paste0("https://www.sec.gov/Archives/edgar/full-index/2016/QTR1/master.idx")
master <- readLines(url(name))
master <- master[grep("SC 13(D|G)", master)]
master <- gsub("#", "", master)
master_table <- fread(textConnection(master), sep = "|")

最后一行返回错误。我验证了textConnection 按预期工作,我可以使用readLines 从中读取,但fread 返回错误。 read.table 遇到了同样的问题。

Error in fread(textConnection(master), sep = "|") :  input= must be a single character string containing a file name, a system command containing at least one space, a URL starting 'http[s]://', 'ftp[s]://' or 'file://', or, the input data itself containing at least one \n or \r

我做错了什么?

【问题讨论】:

  • 我的解决方法是使用read.delim,然后使用setDT,但我仍然不明白出了什么问题。

标签: r data.table fread read.table


【解决方案1】:

1) 在第一行我们不需要paste。在下一行我们不需要url(...)。此外,我们将输入限制为 1000 行,以便在更短的时间内说明该示例。如果我们在fread 中指定na.strings,我们可以省略gsub。此外,将输入折叠为单个字符串允许消除 fread 中的 textConnection

library(data.table)

name <- "https://www.sec.gov/Archives/edgar/full-index/2016/QTR1/master.idx"
master <- readLines(name, 1000)
master <- master[grep("SC 13(D|G)", master)]
master <- paste(master, collapse = "\n")
master_table <- fread(master, sep = "|", na.strings = "")

2) 第二种可能更快的方法是先下载文件然后fread 它,如图所示。

name <- "https://www.sec.gov/Archives/edgar/full-index/2016/QTR1/master.idx"
download.file(name, "master.txt")
master_table <- fread('findstr "SC 13[DG]" master.txt', sep = "|", na.strings = "")

以上内容适用于 Windows。对于带有 bash 的 Linux,将最后一行替换为:

master_table <- fread("grep 'SC 13[DG]' master.txt", sep = "|", na.strings = "")

【讨论】:

    【解决方案2】:

    我不太确定更广泛的背景,尤其是您是否需要使用fread(),但是

    s <- scan(text=master, sep="|", what=character())
    

    效果很好,速度很快(0.1 秒)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-24
      • 2017-10-26
      • 1970-01-01
      • 2013-03-03
      • 1970-01-01
      • 2021-05-27
      • 2012-09-07
      相关资源
      最近更新 更多