【问题标题】:Is possible to use fwrite from `data.table` with gzfile?是否可以将“data.table”中的 fwrite 与 gzfile 一起使用?
【发布时间】:2017-03-14 14:15:39
【问题描述】:

我在 ssh 服务器中运行 R 会话,但我的存储容量有限。我想知道是否有允许压缩的fwrite 实现?比如:

z <- gzfile("file.csv.gz")
fwrite(object, z)

【问题讨论】:

    标签: r compression data.table


    【解决方案1】:

    更新:截至 2019 年 10 月 3 日,以下更改也在 CRAN 上发布(从版本 1.12.4 开始),所以现在一个简单的install.packages("data.table") 就足够了。

    data.table 现在支持 fwrite() 直接到 gzip 压缩的 csvs。截至 2019 年 8 月 28 日,它尚未在 CRAN 上发布,但您可以通过从 GitHub 安装获得它:

    # Install development version of data.table
    install.packages("data.table", repos="https://Rdatatable.gitlab.io/data.table")
    
    # Generate some data
    library(data.table)
    dt <- data.table(
      state = sample(state.name, size = 1e6, replace = TRUE),
      measure = runif(1e6)
    )
    
    # Write to a gzipped file
    data.table::fwrite(dt, file = "dt.gz")
    
    # Read back
    library(R.utils)
    dt2 <- data.table::fread("dt.gz")
    

    【讨论】:

      【解决方案2】:

      您可以使用 R.utils 中的 gzip 功能:

      library(R.utils)
      library(data.table)
      
      #Write gzip file
      df <- data.table(var1='Compress me',var2=', please!')
      fwrite(df,'filename.csv',sep=',')
      gzip('filename.csv',destname='filename.csv.gz')`
      
      # Read gzip file
      fread('gzip -dc filename.csv.gz')
                var1      var2
      1: Compress me , please!
      

      【讨论】:

        【解决方案3】:

        data.table::fwrite 不支持连接。如果您确实需要附加数据,请使用 iotools::write.csv.rawgzfile 连接。否则,您应该改用writeRDSfst::write_fst

        【讨论】:

          猜你喜欢
          • 2018-04-22
          • 2018-08-07
          • 2021-10-11
          • 2021-11-12
          • 2016-04-01
          • 2011-01-20
          • 2018-08-11
          • 2021-08-05
          • 2019-03-18
          相关资源
          最近更新 更多