读取CSV文件,使用连接在各行之间循环

时间:2018-10-24 15:01:35

标签: r csv bigdata

所以我有一个很大的csv excel文件,如果没有rstudio终止,我的计算机将无法处理打开。

为解决此问题,我尝试遍历文件的各行,以便一次对每一行进行计算,然后再存储值,然后继续进行下一行。

通常我可以通过简单地在Rstudio中读取和存储整个csv文件并运行一个简单的for循环来实现(例如,在较小的文件上)。

但是,这是我要避免的这种数据存储的大小,因此我试图一次读取一行csv文件。

(我认为这很有意义)

建议:here

我设法使我的计算结果可以读取并快速处理数据文件的第一行。

这是我正在努力解决的循环,因为我尝试使用for循环(可能应该使用while / if语句),但是我无处可从内部调用“ i”值循环:我的代码的一部分在下面:

con = file(FileName, "r")
  for (row in 1:nrow(con)) {
    data <- read.csv(con, nrow=1) #reading of file
 "insert calculations here"
}

因此没有调用"row",因此循环仅执行一次。我还遇到了"1:nrow(con)"的问题,因为显然nrow(con)仅返回了NULL

任何对此的帮助都会很棒, 谢谢。

2 个答案:

答案 0 :(得分:1)

您可以一次读取10,000行的数据(但您可以更改n以完成所需的次数),进行计算,然后将更改写入新文件,并附加每批到文件末尾。

类似的东西:

i = 0
n = 10000

while (TRUE) {
    df = readr::read_csv('my_file.csv', skip=i, n_max=n)
    # If the number of rows in the file is divisible by n, it may be the case
    # that the next pass will result in an empty data.frame being returned
    if (nrow(df) > 0) {
        # do your calculations
        # If you have performed calculations on df and want to save those results,
        # save the data.frame to a file, appending it to the file to avoid overwriting prior results.
        readr::write_csv(df, 'my_new_file.csv', append=TRUE)
    } else {
        break
    }

    # Check to see if we need to keep going, if so add n to i
    if (nrow(df) < n) {
        break
    } else {
        i = i + n
    }
}

答案 1 :(得分:1)

如果

read.csv()尝试读取文件末尾的内容,则会产生错误。因此,您可以执行以下操作:

con <- file(FileName, "rt")
repeat {
   data <- try(read.csv(con, nrow = 1, header = FALSE), silent = TRUE) #reading of file
   if (inherits(data, "try-error")) break
   "insert calculations here"
}
close(con)

每次一行仅会很慢,但是如果您的计算代码支持的话,可以批量进行。并且我建议在colClasses调用中使用read.csv()指定列类型,以使R有时不会有不同的猜测。

编辑后添加:

我们被告知,数据集中有3000列整数。第一行仅具有部分标题信息。这段代码可以解决:

n <- 1                           # desired batch size
col.names <- paste0("C", 1:3000) # desired column names
con <- file(FileName, "rt")
readLines(con, 1)                # Skip over bad header row
repeat {

   data <- try(read.csv(con, nrow = n, header = FALSE,
                        col.names = col.names,
                        colClasses = "integer"), 
               silent = TRUE) #reading of file
   if (inherits(data, "try-error")) break
   "insert calculations here"
}
close(con)