[R] Question on Simple Repeated Loops

Berend Hasselman bhh at xs4all.nl
Wed Jun 12 10:43:17 CEST 2013


On 12-06-2013, at 04:53, Abdul Rahman bin Kassim (Dr.) <rahmank at frim.gov.my> wrote:

> 
> Dear R-User,
> 
> Appreciate any helps. It looks simple, but I don't have a clue.
> 
> Given that I have a dataframe of tree population with three variables:
> 
> sp=species ,
> d0=initial_size
> grow=growth increment from initial size per year
> 
> How can I calculate the future growth increment of each tree  for the next 3 years.
> 
> The following Rscript was written,
> 
> #----------
> a0 <- data.frame(d0=seq(5,50,5) , sp=gl(2,5,10),
>   grow=rep(0.5,10))
> a2<- list()
> for( i in 1:3){
>  a1 <- a0$d0+a0$grow
>  a2[[i]] <- cbind(sp=a0$sp,d0=a1+i,yr=i)
>   }
> as.data.frame(do.call(cbind,a2))
> 
>> as.data.frame(do.call(cbind,a2))
>   sp   d0 yr sp   d0 yr sp   d0 yr
> 1   1  6.5  1  1  7.5  2  1  8.5  3
> 2   1 11.5  1  1 12.5  2  1 13.5  3
> 3   1 16.5  1  1 17.5  2  1 18.5  3
> 4   1 21.5  1  1 22.5  2  1 23.5  3
> 5   1 26.5  1  1 27.5  2  1 28.5  3
> 6   2 31.5  1  2 32.5  2  2 33.5  3
> 7   2 36.5  1  2 37.5  2  2 38.5  3
> 8   2 41.5  1  2 42.5  2  2 43.5  3
> 9   2 46.5  1  2 47.5  2  2 48.5  3
> 10  2 51.5  1  2 52.5  2  2 53.5  3
> 
> #-----
> 
> but the results did not produce the expected future d0. I think its my R script  "d0=a1+i"  in the  " a2[[i]] <- cbind(sp=a0$sp,d0=a1+i,yr=i)". Interested to know the correct way of writing the repeated loops in R.
> 
> The expected results is:
> 
>   sp   d0 yr sp   d0 yr sp   d0 yr
> 1   1  6.5  1  1  7.0  2  1  7.5  3
> 2   1 11.5  1  1 12.0  2  1 12.5  3
> 3   1 16.5  1  1 17.0  2  1 17.5  3
> 4   1 21.5  1  1 22.0  2  1 22.5  3
> 5   1 26.5  1  1 27.0  2  1 27.5  3
> 6   2 31.5  1  2 32.0  2  2 32.5  3
> 7   2 36.5  1  2 37.0  2  2 37.5  3
> 8   2 41.5  1  2 42.0  2  2 42.5  3
> 9   2 46.5  1  2 47.0  2  2 47.5  3
> 10  2 51.5  1  2 52.0  2  2 52.5  3
> 

Why is the expression  a1 <- a0$d0+a0$grow inside the for loop?
It doesn't depend on i.

I don't understand your expected result.
Fpr species 1 the initial value in column d0 is 5. I assume that this is in year 0.
So with a growth increment of .5 in year 1 I would expect d0 to be 5.5, in year 2it is  6 and in year 3 it would be 6.5.

So see if this does what you seem to want (and remove the redundant expression for a1)

a3<- list()
for( i in 1:3){
 a3[[i]] <- cbind(sp=a0$sp,d0=a0$d0+i*a0$grow,yr=i)
}
as.data.frame(do.call(cbind,a3))
#    sp   d0 yr sp d0 yr sp   d0 yr
# 1   1  5.5  1  1  6  2  1  6.5  3
# 2   1 10.5  1  1 11  2  1 11.5  3
# 3   1 15.5  1  1 16  2  1 16.5  3
# 4   1 20.5  1  1 21  2  1 21.5  3
# 5   1 25.5  1  1 26  2  1 26.5  3
# 6   2 30.5  1  2 31  2  2 31.5  3
# 7   2 35.5  1  2 36  2  2 36.5  3
# 8   2 40.5  1  2 41  2  2 41.5  3
# 9   2 45.5  1  2 46  2  2 46.5  3
# 10  2 50.5  1  2 51  2  2 51.5  3


Berend



More information about the R-help mailing list