【发布时间】: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)
附上文件的输出:
我的问题是:
如何在不下载到 R 的情况下从文件中删除空白行?
故意将 colnames 的二进制向量粘贴为数据框。否则,列名被写为一列向量。也许可以在'writeBin()'之前删除一个空行?如何使文件中的所有数值都写成数字而不是字符?
我故意使用二进制数据传输,因为它比“write.csv2”快得多。例如,如果你申请
system.time(write.table.raw(n,"test.csv",sep=";",col.names=TRUE))
所用时间将比使用的“write.table”少约 4 倍。
【问题讨论】: