[英]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.