0

I made these for loops but they are taking to long to run because of the size of my data. Is there anyway to rewrite my for loops for it to do the same thing but take less time

for (i in 1:length(dataSL_desktop$usid)) {
  usID <- dataSL_desktop$usid[i]
  dates <- seq(as.Date(dataSL_desktop$endTimeStamp[i])-30, by = "day", length = 30)
  x <- rep(0,30)
  for (k in 1:length(datadesktop$Date)) {
    for (j in 1:length(dates)) {
      if (datadesktop$usID[k] == usID & dates[j] == datadesktop$Date[k] ) {
        x[j] <- datadesktop$Visits[k]
      }
    }
  }
}
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
Hike
  • 9
  • 2
  • 3
    As more people will probably tell you, looping is generally frowned upon in R scripts because there are more efficient ways to perform the same operation. – Tim Biegeleisen Dec 17 '15 at 04:28
  • you should read Circle 3 of http://www.burns-stat.com/pages/Tutor/R_inferno.pdf – RockScience Dec 17 '15 at 04:40
  • Try `apply` series function as much as possible. And if you can create a reproducible case, it would be more helpful. – Patric Dec 17 '15 at 04:41
  • 4
    vectorize, vectorize, vectorize, vectorize, vectorize – MichaelChirico Dec 17 '15 at 04:41
  • 2
    @Patric `apply` functions are just loops, they are [not really faster](http://stackoverflow.com/questions/2275896/is-rs-apply-family-more-than-syntactic-sugar). The only solution is to vectorize as much as possible, and when not possible, 1) to put as much as possible outside the loop and 2) to loop over the smallest number of elements – RockScience Dec 17 '15 at 04:45
  • @RockScience, yes, I agree. And for more, I think it should be vectorize > apply > for-loop regarding speed. – Patric Dec 17 '15 at 04:47
  • 2
    Please include some example data in your example to understand what you are doing and to be able to provide help. – Robert Hijmans Dec 17 '15 at 05:15

0 Answers0