R - Reading STDIN line by line

前端 未结 1 1454
执念已碎
执念已碎 2020-12-31 09:47

I want to stream a big data table into R LINE BY LINE, and if the current line has a specific condition (lets say the first columns is >15), add the line to a data frame in

1条回答
  •  南笙
    南笙 (楼主)
    2020-12-31 10:38

    I think it would be wiser to use an R function like readLines. readLines supports only reading a specified number of lines, e.g. 1. Combine that with opening a file connection first, and then calling readLines repeatedly gets you what you want. When calling readLines multiple times, the next n lines are read from the connection. In R code:

    stop = FALSE
    f = file("/tmp/test.txt", "r")
    while(!stop) {
      next_line = readLines(f, n = 1)
      ## Insert some if statement logic here
      if(length(next_line) == 0) {
        stop = TRUE
        close(f)
      }
    }
    

    Additional comments:

    • R has an internal way of treating stdin as file: stdin(). I suggest you use this instead of using pipe('cat /dev/stdin'). This probably makes it more robust, and definitely more cross-platform.
    • You initialize Mydata at the beginning and keep growing it using rbind. If the number of lines that you rbind becomes larger, this will get really slow. This has to do with the fact that when the object grows, the OS needs to find a new memory location for it, which ends up taking a lot of time. Better is to pre-allocate MyData, or use apply style loops.

    0 讨论(0)
提交回复
热议问题