如何将二进制数据写入R中的csv文件

时间:2016-02-12 15:55:39

标签: r csv

我正在尝试将二进制数据写入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)

附上文件的输出:

enter image description here

我的问题是

  1. 如何从文件中删除空行而不下载到R?
    它的目的是将一个二进制矢量的colnames粘贴为数据帧。否则,colnames被写为一列向量。也许可以在'writeBin()'之前删除一个空行?

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

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

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

    经过的时间将是使用'write.table'的4倍。

1 个答案:

答案 0 :(得分:1)

由于我的声誉,我无法对你的问题发表评论,但我希望它可以帮助你。

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

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