[R] Help with loops and how R stores data

(Ted Harding) Ted.Harding at manchester.ac.uk
Mon Feb 4 09:18:12 CET 2008


On 02-Feb-08 21:16:41, R-novice wrote:
> 
> I am trying to make an array c(3,8) that contains the averages of what
> is in another array c(9,8).  I want to average rows 1:3, 4:6, 7:9 and
> have a loop replace the generic 1:24 values in my array with the
> average of the three rows.  
> 
> The problem I am having is that R only replaces the last value from the
> loops, and I am not experienced enough with R to know how it stores
> data when looping and how to overcome this problem. By having it print
> the avg, I was expecting to see 24 numbers, but it only gives me one. 
> 
> Here is my code.
> 
> cts.sds<-array(1:24,c(3,8))
> for(i in 3){
>   for(j in 8){
>     avg<-sum(exprdata[3*i-2:3*i,j]/3)
>     cts.sds[i,j]<-avg
>     print(avg)
>   }
> }
> print(cts.sds)
> 
> Any help with this pesky matter will be greatly appreciated.

I think you have made two types of mistake here.

1. You wrote "for(i in 3)" and "for(i in 3)". This means that
'i' will take only one value, namely 3; and 'j' will take only
one value, namely 8. If you wanted to loop over i = 1,2,3 and
j=1,2,3,4,5,6,7,8 then you should write

  for(i in (1:3)){ for(j in (1:8){ ... }}

2. This is more subtle, and you're far from the only person
to have tripped over this one.

Because of the order of precedence of the operators, in the
epression

  3*i-2:3*i

for each value of 'i' it will first evaluate "2:3", namely {2,3},
and then evaluate the remainder. So, for say i=2, you will get
two numbers 3*i-2*i = 2 and 3*i-3*i = 0, whereas what you
presumably intended was (3*i-2):(3*i) = 4:6 = {4,5,6}.

The way to avoid this trap is to use parantheses to force the
order of evaluation you want:

  avg<-sum(exprdata[(3*i-2):(3*i,j)]/3)

Example:
  i<-2
  3*i-2:3*i
# [1] 2 0
  (3*i-2):(3*i)
# [1] 4 5 6

The reason is that the ":" operator takes precedence over the
binary operators "*", "+" and "-".

Enter

  ?Syntax

to get a listing of the various operators in order of
precedence.

Hoping this helps,
Ted.

--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 04-Feb-08                                       Time: 08:18:05
------------------------------ XFMail ------------------------------



More information about the R-help mailing list