[R] problem accumulating array within a function over loops

Jonathan Williams jonathan.williams at pharmacology.oxford.ac.uk
Wed Oct 5 11:46:54 CEST 2005


Dear R helpers,

I am having trouble with an array inside a loop.

I wish to accumulate the results of a function in an array within
the function, over several loops of a program outside the function.

The problem is that the array seems to re-set at every entry to the
function. Here is an example, so you can see what I mean.

########################################################################
#First, I declare the array and loop control variables
maxrun=3; a=array(NA, c(3,5)); run=0

# Then I define the function "testf"
testf=function(x,y){
print(paste('Run:',run)) #check that the function knows about "run"
a[run,1:3]=runif(3); a[run,4]=x; a[run,5]=y #collect numbers into array "a"
print(paste("Row", run, "of a:")); print(a[run,]) #check what row 'run' of
"a" contains
print("Whole of a:"); print(a) # check what all of "a" contains
}

#Finally, I loop through "testf" maxrun occasions
for (run in 1:maxrun) testf(run,run*10)
#########################################################################

Here is the output:-

[1] "Run: 1"
[1] "Row 1 of a:"
[1]  0.4637560  0.8872455  0.6421500  1.0000000 10.0000000
[1] "Whole of a:"
          [,1]      [,2]    [,3] [,4] [,5]
[1,] 0.4637560 0.8872455 0.64215    1   10
[2,]        NA        NA      NA   NA   NA
[3,]        NA        NA      NA   NA   NA
[1] "Run: 2"
[1] "Row 2 of a:"
[1]  0.4841261  0.8835118  0.9862266  2.0000000 20.0000000
[1] "Whole of a:"
          [,1]      [,2]      [,3] [,4] [,5]
[1,]        NA        NA        NA   NA   NA
[2,] 0.4841261 0.8835118 0.9862266    2   20
[3,]        NA        NA        NA   NA   NA
[1] "Run: 3"
[1] "Row 3 of a:"
[1]  0.7638856  0.6667588  0.6102928  3.0000000 30.0000000
[1] "Whole of a:"
          [,1]      [,2]      [,3] [,4] [,5]
[1,]        NA        NA        NA   NA   NA
[2,]        NA        NA        NA   NA   NA
[3,] 0.7638856 0.6667588 0.6102928    3   30

You can see that array a correctly collects the numbers at each loop.
But, each successive loop loses the contents of previous loops. I am
hoping to keep the results of each successive loop in "a", so that
after maxrun runs, "a" looks like:-

          [,1]      [,2]    [,3]   [,4] [,5]
[1,] 0.4637560 0.8872455 0.64215      1   10
[2,] 0.4841261 0.8835118 0.9862266    2   20
[3,] 0.7638856 0.6667588 0.6102928    3   30

(I have made this by cutting and pasting from the above output, to show
what I hoped testf would produce).

I am sure I must be making a simple but fundamental error. Would
someone be so kind as to show me what this is and how to correct it?
I have struggled with it for over an hour, without success!!!!!
I am running R 2.1.1 on a Windows 2000 machine.

Thanks, in advance, for your help,

Jonathan Williams




More information about the R-help mailing list