Skip to content

Optimize code to read text-file with digits

10 messages · Martin Møller Skarbiniks Pedersen, PIKAL Petr, Peter Dalgaard +2 more

#
Hi,

  Every day I try to write some small R programs to improve my R-skills.
  Yesterday I wrote a small program to read the digits from "A Million
Random Digits" from RAND.
  My code works but it is very slow and I guess the code is not optimal.

The digits.txt file downloaded from
https://www.rand.org/pubs/monograph_reports/MR1418.html
contains 20000 lines which looks like this:
00000   10097 32533  76520 13586  34673 54876  80959 09117  39292 74945
00001   37542 04805  64894 74296  24805 24037  20636 10402  00822 91665
00002   08422 68953  19645 09303  23209 02560  15953 34764  35080 33606
00003   99019 02529  09376 70715  38311 31165  88676 74397  04436 27659
00004   12807 99970  80157 36147  64032 36653  98951 16877  12171 76833

My program which is slow looks like this:

filename <- "digits.txt"
lines <- readLines(filename)

numbers <- vector('numeric')
for (i in 1:length(lines)) {

    # remove first column
    lines[i] <- sub("[^ ]+ +","",lines[i])

    # remove spaces
    lines[i] <- gsub(" ","",lines[i])

    # split the characters and convert them into numbers
    numbers <- c(numbers,as.numeric(unlist(strsplit(lines[i],""))))
}

Thanks for any advice how this program can be improved.

Regards
Martin M. S. Pedersen
#
Hi

see in line
why you do not read a file as a whole e.g. by

lines<-read.table("digits.txt")

After that you do not need for cycle (but maybe I misunderstand what you really want)

remove first column

lines <- lines[,-1]

And now I am lost.
Do you want each row convert into a numeric vector? It probably exceed the precision of biggest number allowed.

Do you want to split each column to 5 numeric columns?
you can use something like

outer(lines[,1], 10^c(4:0), function(a, b) a %/% b %% 10)

to split the first column.

Or do you want one big numeric vector from all your numbers?

here you need to read values as character variables

lines<-read.table("digits.txt", colClasses="character")
numbers<-as.numeric(unlist(strsplit(as.character(lines[1,]),"")))
changes first row to numeric vector.

Anyway, can you explain what is your final goal?

Cheers
Petr
________________________________
Tento e-mail a jak?koliv k n?mu p?ipojen? dokumenty jsou d?v?rn? a jsou ur?eny pouze jeho adres?t?m.
Jestli?e jste obdr?el(a) tento e-mail omylem, informujte laskav? neprodlen? jeho odes?latele. Obsah tohoto emailu i s p??lohami a jeho kopie vyma?te ze sv?ho syst?mu.
Nejste-li zam??len?m adres?tem tohoto emailu, nejste opr?vn?ni tento email jakkoliv u??vat, roz?i?ovat, kop?rovat ?i zve?ej?ovat.
Odes?latel e-mailu neodpov?d? za eventu?ln? ?kodu zp?sobenou modifikacemi ?i zpo?d?n?m p?enosu e-mailu.

V p??pad?, ?e je tento e-mail sou??st? obchodn?ho jedn?n?:
- vyhrazuje si odes?latel pr?vo ukon?it kdykoliv jedn?n? o uzav?en? smlouvy, a to z jak?hokoliv d?vodu i bez uveden? d?vodu.
- a obsahuje-li nab?dku, je adres?t opr?vn?n nab?dku bezodkladn? p?ijmout; Odes?latel tohoto e-mailu (nab?dky) vylu?uje p?ijet? nab?dky ze strany p??jemce s dodatkem ?i odchylkou.
- trv? odes?latel na tom, ?e p??slu?n? smlouva je uzav?ena teprve v?slovn?m dosa?en?m shody na v?ech jej?ch n?le?itostech.
- odes?latel tohoto emailu informuje, ?e nen? opr?vn?n uzav?rat za spole?nost ??dn? smlouvy s v?jimkou p??pad?, kdy k tomu byl p?semn? zmocn?n nebo p?semn? pov??en a takov? pov??en? nebo pln? moc byly adres?tovi tohoto emailu p??padn? osob?, kterou adres?t zastupuje, p?edlo?eny nebo jejich existence je adres?tovi ?i osob? j?m zastoupen? zn?m?.

This e-mail and any documents attached to it may be confidential and are intended only for its intended recipients.
If you received this e-mail by mistake, please immediately inform its sender. Delete the contents of this e-mail with all attachments and its copies from your system.
If you are not the intended recipient of this e-mail, you are not authorized to use, disseminate, copy or disclose this e-mail in any manner.
The sender of this e-mail shall not be liable for any possible damage caused by modifications of the e-mail or by delay with transfer of the email.

In case that this e-mail forms part of business dealings:
- the sender reserves the right to end negotiations about entering into a contract in any time, for any reason, and without stating any reasoning.
- if the e-mail contains an offer, the recipient is entitled to immediately accept such offer; The sender of this e-mail (offer) excludes any acceptance of the offer on the part of the recipient containing any amendment or variation.
- the sender insists on that the respective contract is concluded only upon an express mutual agreement on all its aspects.
- the sender of this e-mail informs that he/she is not authorized to enter into any contracts on behalf of the company except for cases in which he/she is expressly authorized to do so in writing, and such authorization or power of attorney is submitted to the recipient or the person represented by the recipient, or the existence of such authorization is known to the recipient of the person represented by the recipient.
#
On 8 September 2017 at 11:25, PIKAL Petr <petr.pikal at precheza.cz> wrote:

            
Good idea.
[...]
here you need to read values as character variables
Yes. That's what I am looking for.
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,]),""))))
}
A numeric vector of length 1 million. Each element should be one digit.
Thanks.
/Martin
#
Simplest version that I can think of:

x <- scan("~/Downloads/digits.txt")
x <- x[-seq(1,220000,11)]
length(x) # 200000
hist(x)

Now, because it's Friday: 

How does one work out the theoretical distribution of the following table?
0     1     2     3     4     5     6     7     8     9    10    11 
13497 27113 27010 18116  9122  3466  1186   366    99    22     1     1 
   12 
    1 

(I.e., out of 200000 random 5 digit numbers, 13497 numbers never occurred, 27113 numbers exactly once, and ... and 1 number occurred 12 times.)

-pd

  
    
#
Hi

see in line
*********************

Well, this is how you cen get your numeric vector of length 1e6

set.seed(111)
numbers0<-sample(0:9, 1e6, replace=TRUE)

If you want to get this number vector from the file it is better to use lists and lapply but maybe with loop it can be done too

First I prepare some data>

daf<-as.character(numbers0)
index<- 0:(1e6-1)
index<-index%/%5
lll<-split(daf, index)
lll<-lapply(lll, paste, collapse="")
daf<-do.call(rbind, lll)
dim(daf)<-c(20000,10)
daf<-as.data.frame(daf)

# here we have data frame similar to what you can get with read.table
head(daf)
     V1    V2    V3    V4    V5    V6    V7    V8    V9   V10
1 57353 75381 66866 52351 03707 13763 76897 67383 02972 37636
2 40540 52811 02521 18199 23236 64967 70123 46962 95347 47379
3 55001 55094 36922 08811 77704 99060 65902 28279 29131 98979
4 41936 77976 71345 84996 36865 11825 11024 90616 35653 10772
5 42339 89821 23790 62176 03266 36054 34882 06822 10087 05317
6 36275 45199 80796 54458 38836 87953 64394 02685 25788 19502
# now it is time transform data.frame to numeric vector
# Change to list, transform to character, split to items, unlist and make numeric
lll<- as.list(daf)
lll<-lapply(lll, as.character)
numbers<-lapply(lll, strsplit,"")
numbers <- as.numeric(unlist(numbers))
length(numbers)
[1] 1000000
[1] TRUE
all this is computed in less than 1 second, is it really so slow?

Cheers
Petr

******************
________________________________
Tento e-mail a jak?koliv k n?mu p?ipojen? dokumenty jsou d?v?rn? a jsou ur?eny pouze jeho adres?t?m.
Jestli?e jste obdr?el(a) tento e-mail omylem, informujte laskav? neprodlen? jeho odes?latele. Obsah tohoto emailu i s p??lohami a jeho kopie vyma?te ze sv?ho syst?mu.
Nejste-li zam??len?m adres?tem tohoto emailu, nejste opr?vn?ni tento email jakkoliv u??vat, roz?i?ovat, kop?rovat ?i zve?ej?ovat.
Odes?latel e-mailu neodpov?d? za eventu?ln? ?kodu zp?sobenou modifikacemi ?i zpo?d?n?m p?enosu e-mailu.

V p??pad?, ?e je tento e-mail sou??st? obchodn?ho jedn?n?:
- vyhrazuje si odes?latel pr?vo ukon?it kdykoliv jedn?n? o uzav?en? smlouvy, a to z jak?hokoliv d?vodu i bez uveden? d?vodu.
- a obsahuje-li nab?dku, je adres?t opr?vn?n nab?dku bezodkladn? p?ijmout; Odes?latel tohoto e-mailu (nab?dky) vylu?uje p?ijet? nab?dky ze strany p??jemce s dodatkem ?i odchylkou.
- trv? odes?latel na tom, ?e p??slu?n? smlouva je uzav?ena teprve v?slovn?m dosa?en?m shody na v?ech jej?ch n?le?itostech.
- odes?latel tohoto emailu informuje, ?e nen? opr?vn?n uzav?rat za spole?nost ??dn? smlouvy s v?jimkou p??pad?, kdy k tomu byl p?semn? zmocn?n nebo p?semn? pov??en a takov? pov??en? nebo pln? moc byly adres?tovi tohoto emailu p??padn? osob?, kterou adres?t zastupuje, p?edlo?eny nebo jejich existence je adres?tovi ?i osob? j?m zastoupen? zn?m?.

This e-mail and any documents attached to it may be confidential and are intended only for its intended recipients.
If you received this e-mail by mistake, please immediately inform its sender. Delete the contents of this e-mail with all attachments and its copies from your system.
If you are not the intended recipient of this e-mail, you are not authorized to use, disseminate, copy or disclose this e-mail in any manner.
The sender of this e-mail shall not be liable for any possible damage caused by modifications of the e-mail or by delay with transfer of the email.

In case that this e-mail forms part of business dealings:
- the sender reserves the right to end negotiations about entering into a contract in any time, for any reason, and without stating any reasoning.
- if the e-mail contains an offer, the recipient is entitled to immediately accept such offer; The sender of this e-mail (offer) excludes any acceptance of the offer on the part of the recipient containing any amendment or variation.
- the sender insists on that the respective contract is concluded only upon an express mutual agreement on all its aspects.
- the sender of this e-mail informs that he/she is not authorized to enter into any contracts on behalf of the company except for cases in which he/she is expressly authorized to do so in writing, and such authorization or power of attorney is submitted to the recipient or the person represented by the recipient, or the existence of such authorization is known to the recipient of the person represented by the recipient.
#
...and, come to think of it, if you really want the 1000000 random digits:

xx <- c(outer(x,10^(0:4), "%/%")) %% 10
#
On 8 September 2017 at 14:37, peter dalgaard <pdalgd at gmail.com> wrote:
Hi Peter,
  Thanks a lot for the answers. I can see that I need to read about outer().
  However I get a different result than expected.

R> x <- scan("digits.txt")
Read 220000 items

R> head(x)
[1]     0 10097 32533 76520 13586 34673

R> x <- x[-seq(1,220000,11)]
R> head(x)
[1] 10097 32533 76520 13586 34673 54876

R> head(c(outer(x,10^(0:4), "%/%")) %% 10, 10) #
[1] 7 3 0 6 3 6  9 7 2 5

Regards
Martin
#
Ah, right. You do get all the digits, but in the order of the last digit of each 5 digit number, then all the penultimate digits, etc. To get digits in the right order, try
[1] 1 0 0 9 7 3 2 5 3 3 7 6 5 2 0 1 3 5 8 6 3 4 6 7 3 5 4 8 7 6 8 0 9 5
 [35] 9 0 9 1 1 7 3 9 2 9 2 7 4 9 4 5 3 7 5 4 2 0 4 8 0 5 6 4 8 9 4 7 4 2
 [69] 9 6 2 4 8 0 5 2 4 0 3 7 2 0 6 3 6 1 0 4 0 2 0 0 8 2 2 9 1 6 6 5

I.e., reverse the order of digit generation and transpose the matrix that outer() creates (because matrices are column-major).

  
    
#
>> On 8 Sep 2017, at 15:51 , Martin M?ller Skarbiniks
>> Pedersen <traxplayer at gmail.com> wrote:
>> 
    >> On 8 September 2017 at 14:37, peter dalgaard
>> <pdalgd at gmail.com> wrote:
>>> 
    >>> 
    >>>> On 8 Sep 2017, at 14:03 , peter dalgaard
>>>> <pdalgd at gmail.com> wrote:
>>>> 
    >>>> x <- scan("~/Downloads/digits.txt") x <-
    >>>> x[-seq(1,220000,11)]
    >>> 
    >>> ...and, come to think of it, if you really want the
    >>> 1000000 random digits:
    >>> 
    >>> xx <- c(outer(x,10^(0:4), "%/%")) %% 10
    >>> 
    >> 
    >> Hi Peter, Thanks a lot for the answers. I can see that I
    >> need to read about outer().  However I get a different
    >> result than expected.
    >> 
    R> x <- scan("digits.txt")
    >> Read 220000 items
    >> 
    R> head(x)
    >> [1] 0 10097 32533 76520 13586 34673
    >> 
    R> x <- x[-seq(1,220000,11)] head(x)
    >> [1] 10097 32533 76520 13586 34673 54876
    >> 
    R> head(c(outer(x,10^(0:4), "%/%")) %% 10, 10) #
    >> [1] 7 3 0 6 3 6 9 7 2 5
    >> 

    > Ah, right. You do get all the digits, but in the order of
    > the last digit of each 5 digit number, then all the
    > penultimate digits, etc. To get digits in the right order,
    > try

    >> xx <- c(t(outer(x,10^(4:0), "%/%"))) %% 10 head(xx, 100)
    >   [1] 1 0 0 9 7 3 2 5 3 3 7 6 5 2 0 1 3 5 8 6 3 4 6 7 3 5
    > 4 8 7 6 8 0 9 5 [35] 9 0 9 1 1 7 3 9 2 9 2 7 4 9 4 5 3 7 5
    > 4 2 0 4 8 0 5 6 4 8 9 4 7 4 2 [69] 9 6 2 4 8 0 5 2 4 0 3 7
    > 2 0 6 3 6 1 0 4 0 2 0 0 8 2 2 9 1 6 6 5

    > I.e., reverse the order of digit generation and transpose
    > the matrix that outer() creates (because matrices are
    > column-major).

As people are  "exercising" with R and it's Friday:

Try to use  read.fwf() instead of scan() to get to the digits directly,
and see if you get the identical digits, and if it is faster overall or not
[I have no idea of the answer to that].

another Martin.
#
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: