[R] What is wrong with this FOR-loop?

Barry Rowlingson B.Rowlingson at lancaster.ac.uk
Mon Dec 5 12:56:06 CET 2005


Serguei Kaniovski wrote:
> Hi, I have a more complex example, but the problem boils down to this 
> FOR-loop not filling in the res-matrix

> for(i in run_rows)
> {
>      for(j in run_cols)
>      {
>          res[i,j]=i+j

  have a look at what i and j are in such a loop:

 > for(i in run_rows){
+ print(i)
+ }
[1] 0
[1] 0.05
[1] 0.1
[1] 0.15
[1] 0.2
[1] 0.25

  - and then you are trying to fill res[0.05,.3] and so on. Its not 
going to work!

You probably want something like:

  for(i in 1:length(run_rows)){

so that i is 1,2,3,....

  then you do:

  res[i,j] = run_rows[i] + run_cols[j]

  within your loop...

  ...which in fact can be done in one line, but you need to learn about 
matrix indexing first!

Barry




More information about the R-help mailing list