【问题标题】:How can I use fread to read gz files in R?如何使用 fread 读取 R 中的 gz 文件?
【发布时间】:2016-10-10 05:15:19
【问题描述】:

我在试图加快 read.table 步骤的 Windows 机器上。我的文件都是.gz。

x=paste("gzip -c ",filename,sep="")
phi_raw = fread(x)

Error in fread(x) : 

无法理解错误。对我来说有点太神秘了。

不是 zx8754 建议的重复:专门在 fread 的上下文中使用。虽然 fread dows 没有对 gzip 的原生支持,但这种范例应该可以工作。见http://www.molpopgen.org/coding/datatable.html

更新

以下使用系统的建议会产生更长的错误消息 - 尽管我仍然卡住。

Error in fread(system(x)) : 

  'input' must be a single character string containing a file name, a command, full path to a file, a URL starting 'http[s]://', 'ftp[s]://' or 'file://', or the input data itself

In addition: Warning message:


running command 'gzip -c D:/x_.gz' had status 1

更新

如下所示使用 gunzip 运行:

Error in fread(system(x)) : 

  'input' must be a single character string containing a file name, a command, full path to a file, a URL starting 'http[s]://', 'ftp[s]://' or 'file://', or the input data itself

In addition: Warning message:

running command 'gunzip -c D:/XX_.gz' had status 127

注意不同的状态

【问题讨论】:

  • 不是重复的:专门在 fread 的上下文中使用。虽然 fread dows 没有对 gzip 的原生支持,但这种范例应该可以工作。
  • 错误信息在哪里? fread(system(x)) 怎么样?
  • 我们确定您安装的 Windoze 可以访问 gzip 和 gunzip 吗?还要注意引用的文章使用的是 gunzip 而不是 gzip。

标签: r windows gzip fread


【解决方案1】:

我经常在 Windows 上使用 gzip 和 fread。它读取文件而不解压缩它们。我会尝试使用 gzip 命令添加 -d 选项。具体来说,在您的代码中,尝试x=paste("gzip -dc ",filename,sep="")。这是一个可在我的机器上运行的可重现示例:

df <- data.frame(x = 1:10, y = letters[1:10])
write.table(df, 'df.txt', row.names = F, quote = F, sep = '\t')
system("which gzip")
system("gzip df.txt")
data.table::fread("gzip -dc df.txt")

这是我的sessionInfo()

R version 3.3.1 (2016-06-21)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

loaded via a namespace (and not attached):
[1] rsconnect_0.4.3  tools_3.3.1      data.table_1.9.6 chron_2.3-47 

我已经在 Windows 上成功使用 gzip,而无需使用 Rtools (https://cran.r-project.org/bin/windows/Rtools/) 和 Gow (https://github.com/bmatzelle/gow/wiki) 将解压缩文件添加到我的硬盘驱动器。如果我上面的可重现示例对您不起作用,请使用 which gzipwhich gunzip 命令查看正在运行的确切 .exe。如果不是 Rtools 或 Gow,也许可以尝试安装这两个中的一个并再次尝试可重现的示例。

【讨论】:

    【解决方案2】:

    data.table 现在支持使用fread 函数直接读取.gz 文件,前提是安装了R.utils 包。

    正如this answer 中对类似问题的建议,您可以简单地运行以下命令:

    library(data.table)
    phi_raw <- fread("filename.gz")
    

    【讨论】:

      猜你喜欢
      • 2022-07-15
      • 1970-01-01
      • 1970-01-01
      • 2017-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      相关资源
      最近更新 更多