Skip to content
Prev 371282 / 398530 Next

Optimize code to read text-file with digits

Remove the for loop and all the [i]'s in your code and it will probably go
faster.  I.e., change

f0 <- function (lines)
{
    numbers <- vector("numeric")
    for (i in 1:length(lines)) {
        lines[i] <- sub("[^ ]+ +", "", lines[i])
        lines[i] <- gsub(" ", "", lines[i])
        numbers <- c(numbers, as.numeric(unlist(strsplit(lines[i],
            ""))))
    }
    numbers
}

to

f1 <- function (lines)
{
    lines <- sub("[^ ]+ +", "", lines)
    lines <- gsub(" ", "", lines)
    as.numeric(unlist(strsplit(lines, "")))
}

I haven't measured it, but the big time sink may come from f0 growing the
'numbers' vector bit by bit.  That can cause a lot of reallocations and
garbage collections.

Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Fri, Sep 8, 2017 at 1:48 AM, Martin M?ller Skarbiniks Pedersen <
traxplayer at gmail.com> wrote: