我正在 R 中逐行读取一个大型 CSV 文件(>15 GB)。我正在使用
con <- file("datafile.csv", open = "r")
while (length(oneLine <- readLines(con, n = 1, warn = FALSE)) > 0) {
# code to be written
}
在“要编写的代码”部分,我需要能够引用每一行中的各个元素并将它们保存到一个数组中。如果这很重要,该文件没有标题。
谢谢!
我正在 R 中逐行读取一个大型 CSV 文件(>15 GB)。我正在使用
con <- file("datafile.csv", open = "r")
while (length(oneLine <- readLines(con, n = 1, warn = FALSE)) > 0) {
# code to be written
}
在“要编写的代码”部分,我需要能够引用每一行中的各个元素并将它们保存到一个数组中。如果这很重要,该文件没有标题。
谢谢!
你可以这样做:
CHUNK_SIZE <- 5000
con <- file('datafile.csv', 'rt')
res <- NULL
while (nrow(chunk <- read.csv(con, nrow = CHUNK_SIZE, header = FALSE, stringsAsFactors = FALSE)) > 0) {
res <- rbind(res, chunk)
if (nrow(chunk) < CHUNK_SIZE) break
}
您可以使用read.table
with 参数text
来解析oneLine
字符串,就好像它是 csv 文件一样:
# set your arguments: separator, decimal separator etc...
x <- read.table(text=oneLine, sep=",", dec=".", header=F)
返回x
的data.frame
只有一行,您可以轻松地将其转换为数组。