Skip to content
Prev 274757 / 398506 Next

How to read data sequentially into R (line by line)?

Let's do it in two parts: first create all the separate files (which
if this what you are after, we can stop here).  You can change the
value on readLines to read in as many lines as you want; I set it to 2
just for testing.

x <- textConnection("APE!KKU!684!
APE!VAL!!
APE!UASU!!
APE!PLA!1!
APE!E!10!
APE!TPVA!17122009!
APE!STAP!1!
GG!KK!KK!
APE!KKU!684!
APE!VAL!!
APE!UASU!!
APE!PLA!1!
APE!E!10!
APE!TPVA!17122009!
APE!STAP!1!
GG!KK!KK!
APE!KKU!684!
APE!VAL!!
APE!UASU!!
APE!PLA!1!
APE!E!10!
APE!TPVA!17122009!
APE!STAP!1!
GG!KK!KK!")

fileNo <- 1  # used for file name
buffer <- NULL
repeat{
    input <- readLines(x, n = 100)
    if (length(input) == 0) break  # done
    buffer <- c(buffer, input)
    # find separator
    repeat{
        indx <- which(grepl("^GG!KK!KK!", buffer))[1]
        if (is.na(indx)) break  # not found yet; read more
        writeLines(buffer[1:(indx - 1L)]
            , sprintf("newFile%04d", fileNo)
            )
        buffer <- buffer[-c(1:indx)]  # remove data
        fileNo <- fileNo + 1
    }
}
On Tue, Oct 18, 2011 at 8:12 AM, johannes rara <johannesraja at gmail.com> wrote: