[R] Optimize code to read text-file with digits
Martin Møller Skarbiniks Pedersen
traxplayer at gmail.com
Fri Sep 8 11:58:22 CEST 2017
On 8 September 2017 at 11:25, PIKAL Petr <petr.pikal at precheza.cz> wrote:
> > Moller Skarbiniks Pedersen
> My program which is slow looks like this:
> >
> > filename <- "digits.txt"
> > lines <- readLines(filename)
>
> why you do not read a file as a whole e.g. by
>
> lines<-read.table("digits.txt")
>
Good idea.
>
> And now I am lost.
[...]
> Or do you want one big numeric vector from all your numbers?
here you need to read values as character variables
>
Yes. That's what I am looking for.
>
> lines<-read.table("digits.txt", colClasses="character")
> numbers<-as.numeric(unlist(strsplit(as.character(lines[1,]),"")))
> changes first row to numeric vector.
>
>
Do I still need to loop through all lines?
It is maybe even slower now.
numbers <- vector('numeric')
for (i in 1:nrows(lines)) {
numbers <- c(numbers, as.numeric(unlist(strsplit(as.
character(lines[i,]),""))))
}
> Anyway, can you explain what is your final goal?
>
>
A numeric vector of length 1 million. Each element should be one digit.
> Cheers
> Petr
>
>
Thanks.
/Martin
[[alternative HTML version deleted]]
More information about the R-help
mailing list