[R] Help to make a for for index

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Tue May 6 00:40:47 CEST 2003


"Ronaldo Reis Jr." <chrysopa at insecta.ufv.br> writes:

> Hi,
> 
> I try to make a vector in a for for loop, but it dont work.
> 
> Look:
> 
> > a <- 0;for(i in c(1:2)) { for(j in c(1:2)) { a <- i+j; print(a)}}
> [1] 2
> [1] 3
> [1] 3
> [1] 4
> 
> I try to make this a vector, like this:
> [1] 2 3 3 4
> 
> > a <- 0;for(i in c(1:2)) { for(j in c(1:2)) { a[j] <- i+j}}; print(a)
> [1] 3 4
> > a <- 0;for(i in c(1:2)) { for(j in c(1:2)) { a[i] <- i+j}}; print(a)
> [1] 3 4
> 
> In this way the vector have only the two last loop.
> 
> I try another way but it dont work.
> 
> How make a correct index for this loop inside loop?

Use a 3rd index:

k <- 0
a <- numeric(4)
for(i in 1:2)
   for(j in 1:2){
       k <- k + 1
       a[k] <- i+j
   }
a

or simply

as.vector(outer(1:2,1:2,"+"))

-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907




More information about the R-help mailing list