Skip to content

Help to make a for for index

4 messages · Ronaldo Reis Jr., Peter Dalgaard, Tony Plate +1 more

#
Hi,

I try to make a vector in a for for loop, but it dont work.

Look:
[1] 2
[1] 3
[1] 3
[1] 4

I try to make this a vector, like this:
[1] 2 3 3 4
[1] 3 4
[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?

Thanks
Ronaldo
#
"Ronaldo Reis Jr." <chrysopa at insecta.ufv.br> writes:
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,"+"))
#
Printing some intermediate expressions can make it clearer what R is trying 
to do:

 > a <- 0;for(i in c(1:2)) { for(j in c(1:2)) { e<-substitute(a[j] <- 
i+j,list(i=i,j=j)); cat("executing:", deparse(e),"\n"); eval(e)}}; print(a)
executing: a[1] <- 1 + 1
executing: a[2] <- 1 + 2
executing: a[1] <- 2 + 1
executing: a[2] <- 2 + 2
[1] 3 4
 >

Perhaps this is what you want: (?)

 > a <- numeric(0);for(i in c(1:2)) { for(j in c(1:2)) { a <- c(a,i+j); 
print(a)}}
[1] 2
[1] 2 3
[1] 2 3 3
[1] 2 3 3 4
 > a
[1] 2 3 3 4
 >

(This is not the most efficient way to construct a vector in a loop, but it 
works and the code captures the spirit of what I'm guessing you were trying 
to do.)

hope this helps,

-- Tony Plate
At Monday 07:22 PM 5/5/2003 -0300, Ronaldo Reis Jr. wrote:
#
Two alternative solutions:

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

a <- rep(NA, 4)
i1 <- 0
for(i in 1:2)for(j in 1:2){
	i1 <- i1+1
	a[i1] <- i+j
}
a

hth.  spencer graves
Ronaldo Reis Jr. wrote: