【问题标题】:how to write binary data to csv file in R如何将二进制数据写入R中的csv文件
【发布时间】:2016-02-12 15:55:38
【问题描述】:

我正在尝试将二进制数据写入 csv 文件,以便使用“read.csv2”、“read.table”或“fread”进一步读取该文件以获取数据帧。脚本如下:

library(iotools)
library(data.table)

#make a dataframe 
n<-data.frame(x=1:100000,y=rnorm(1:100000),z=rnorm(1:100000),w=c("1dfsfsfsf"))

#file name variable 
file_output<-"test.csv"

#check the existence of the file -> if true -> to remove it
if (file.exists(file_output)) file.remove(file_output)
#create a file
file(file_output, ifelse(FALSE, "ab", "wb"))

#to make a file object
zz <- file(file_output, "wb")
#to make a binary vector with column names
rnames<-as.output(rbind(colnames(n),""),sep=";",nsep="\t")
#to make a binary vector with dataframe
r = as.output(n, sep = ";",nsep="\t")

#write column names to the file
writeBin(rnames, zz)
#write data to the file
writeBin(r, zz)
#close file object
close(zz)

#test readings
check<-read.table(file_output,header = TRUE,sep=";",dec=".",stringsAsFactors = FALSE
                  ,blank.lines.skip=T)
str(check)
class(check)

check<-fread(file_output,dec=".",data.table = FALSE,stringsAsFactors = FALSE)
str(check)
class(check)

check<-read.csv2(file_output,dec=".")
str(check)
class(check)

附上文件的输出:

我的问题是

  1. 如何在不下载到 R 的情况下从文件中删除空白行?
    故意将 colnames 的二进制向量粘贴为数据框。否则,列名被写为一列向量。也许可以在'writeBin()'之前删除一个空行?

  2. 如何使文件中的所有数值都写成数字而不是字符?

我故意使用二进制数据传输,因为它比“write.csv2”快得多。例如,如果你申请

system.time(write.table.raw(n,"test.csv",sep=";",col.names=TRUE))

所用时间将比使用的“write.table”少约 4 倍。

【问题讨论】:

    标签: r csv


    【解决方案1】:

    由于我的声誉,我无法对您的问题发表评论,但希望对您有所帮助。

    我想到了两件事
    1. read.table 中使用fill,如果TRUE 在这种情况下,行的长度不相等,则会隐式添加空白字段。 (做??read.table

    2. 你提到了blank.lines.skip=TRUE。如果 TRUE 输入中的空白行被忽略。

    【讨论】:

    • 看看我的“测试阅读”部分——我有这样的选择。但它没有预期的结果。至少在我的工作站上。
    猜你喜欢
    • 2014-03-14
    • 1970-01-01
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多