[英]how to write binary data to csv file in R
我正在尝试将二进制数据写入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倍。
由于我的声誉,我无法评论您的问题,但希望对您有所帮助。
我想到两件事 使用read.table
中的fill
(如果为TRUE
则在这种情况下,行的长度不相等)将隐式添加空白字段。 (做??read.table
)
您已经提到blank.lines.skip=TRUE
。 如果为TRUE
,则输入中的空白行将被忽略。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.