我需要将一个大文件(14 GB)分解成更小的文件。本文件格式为txt,制表符为“;”我知道它有 70 列(字符串、 double )。我想读取 100 万并将它们保存在不同的文件中,file1、file2 ... fileN。
在@MKR 的帮助下
但是过程很慢,我尝试使用 fread,但这是不可能的。
如何优化此代码?
新代码
chunkSize <- 10000
conex <- file(description = db, open = "r")
data <- read.table(conex, nrows = chunkSize, header=T, fill=TRUE, sep =";")
index <- 0
counter <- 0
total <- 0
chunkSize <- 500000
conex <- file(description=db,open="r")
dataChunk <- read.table(conex, nrows=chunkSize, header=T, fill=TRUE,sep=";")
repeat {
dataChunk <- read.table(conex, nrows=chunkSize, header=FALSE, fill = TRUE, sep=";", col.names=db_colnames)
total <- total + sum(dataChunk$total)
counter <- counter + nrow(dataChunk)
write.table(dataChunk, file = paste0("MY_FILE_new",index),sep=";", row.names = FALSE)
if (nrow(dataChunk) != chunkSize){
print('linesok')
break}
index <- index + 1
print(paste('lines', index * chunkSize))
}
最佳答案
不是基于 R 的答案,但在这种情况下,我推荐使用 GNU 的基于 shell 的解决方案 split
.这应该比 R 解决方案快得多。
使用 10^6
将文件拆分为多个块行,你会这样做:
split -l 1000000 my_file.txt
详情
split
,见例如here .
关于r - 在 R 中将大文件分区为小文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50313146/