[R] Speed up or alternative to 'For' loop

2013-06-10 Thread Trevor Walker
I have a For loop that is quite slow and am wondering if there is a faster option: df - data.frame(TreeID=rep(1:500,each=20), Age=rep(seq(1,20,1),500)) df$Height - exp(-0.1 + 0.2*df$Age) df$HeightGrowth - NA #intialize with NA for (i in 2:nrow(df)) {if(df$TreeID[i]==df$TreeID[i-1])

Re: [R] Speed up or alternative to 'For' loop

2013-06-10 Thread Rui Barradas
Hello, One way to speed it up is to use a matrix instead of a data.frame. Since data.frames can hold data of all classes, the access to their elements is slow. And your data is all numeric so it can be hold in a matrix. The second way below gave me a speed up by a factor of 50.

Re: [R] Speed up or alternative to 'For' loop

2013-06-10 Thread MacQueen, Don
How about for (ir in unique(df$TreeID)) { in.ir - df$TreeID == ir df$HeightGrowth[in.ir] - cumsum(df$Height[in.ir]) } Seemed fast enough to me. In R, it is generally good to look for ways to operate on entire vectors or arrays, rather than element by element within them. The cumsum()

Re: [R] Speed up or alternative to 'For' loop

2013-06-10 Thread David Winsemius
On Jun 10, 2013, at 10:28 AM, Trevor Walker wrote: I have a For loop that is quite slow and am wondering if there is a faster option: df - data.frame(TreeID=rep(1:500,each=20), Age=rep(seq(1,20,1),500)) df$Height - exp(-0.1 + 0.2*df$Age) df$HeightGrowth - NA #intialize with NA for (i

Re: [R] Speed up or alternative to 'For' loop

2013-06-10 Thread MacQueen, Don
Sorry, it looks like I was hasty. Absent another dumb mistake, the following should do it. The request was for differences, i.e., the amount of growth from one period to the next, separately for each tree. for (ir in unique(df$TreeID)) { in.ir - df$TreeID == ir df$HeightGrowth[in.ir] - c(NA,

Re: [R] Speed up or alternative to 'For' loop

2013-06-10 Thread MacQueen, Don
Well, speaking of hasty... This will also do it, provided that each tree's initial height is less than the previous tree's final height. In principle, not a safe assumption, but might be ok depending on where the data came from. df$delta - c(NA,diff(df$Height)) df$delta[df$delta 0] - NA -Don

Re: [R] Speed up or alternative to 'For' loop

2013-06-10 Thread arun
Walker trevordaviswal...@gmail.com To: r-help@r-project.org Cc: Sent: Monday, June 10, 2013 1:28 PM Subject: [R] Speed up or alternative to 'For' loop I have a For loop that is quite slow and am wondering if there is a faster option: df - data.frame(TreeID=rep(1:500,each=20), Age=rep(seq(1,20,1