title: For Loop in R (Looking for an alternative)
body: <p>The following code runs a loops but the problem is the speed; it takes several hours to finish and I am looking for an alternative so that I don´t have to wait so long.</p>
  
  <p>Basically what the code does the follolling calculations:</p>
  
  <pre><code>1.-It calculates the mean of the values of the 60 days.
  2.-It gets the standard deviation of the values of the 60 days.
  3.-It gets the Max of the values of the 60 days.
  4.-It gets the Min of the values of the 60 days.
  5.-Then with the previous calculations the code "smooths" the peaks up and down.
  6.-Then the code simply get the means from 60, 30, 15 and 7 Days.
  </code></pre>
  
  <p>So the purpose of these code is to remove the peaks of the data using the method already mentioned.</p>
  
  <p>Here is the code:</p>
  
  <pre><code>options(stringsAsFactors=F)
  
  DAT &lt;- data.frame(ITEM = "x", CLIENT = as.numeric(1:100000), matrix(sample(1:1000, 60, replace=T), ncol=60, nrow=100000, dimnames=list(NULL,paste0('DAY_',1:60))))
  
  DATT &lt;- DAT
  
  nRow &lt;- nrow(DAT)
  TMP  &lt;- NULL
  for(iROW in 1:nRow){#iROW &lt;- 1
   print(c(iROW,nRow))
  
    Demand &lt;- NULL
    for(iCOL in 3:ncol(DAT)){#iCOL &lt;- 1
        Demand  &lt;- c(Demand,DAT[iROW,iCOL])
  
    }
  
    ww &lt;- which(!is.na(Demand))
  
    if(length(ww) &gt; 0){
      Average &lt;- round(mean(Demand[ww]),digits=4)
      DesvEst  &lt;- round(sd(Demand,na.rm=T),digits=4)
      Max      &lt;- round(Average + (1 * DesvEst),digits=4)
      Min      &lt;- round(max(Average - (1 * DesvEst), 0),digits=4)
      Demand  &lt;- round(ifelse(is.na(Demand), Demand, ifelse(Demand &gt; Max, Max, ifelse(Demand &lt; Min, Min, Demand))))
      Prom60   &lt;- round(mean(Demand[ww]),digits=4)
      Prom30   &lt;- round(mean(Demand[intersect(ww,(length(Demand) - 29):length(Demand))]),digits=4)
      Prom15   &lt;- round(mean(Demand[intersect(ww,(length(Demand) - 14):length(Demand))]),digits=4)
      Prom07   &lt;- round(mean(Demand[intersect(ww,(length(Demand) - 6):length(Demand))]),digits=4)
  
    }else{
      Average &lt;- DesvEst &lt;- Max &lt;- Min &lt;- Prom60 &lt;- Prom30 &lt;- Prom15 &lt;- Prom07 &lt;- NA
  
    }
  
    DAT[iROW,3:ncol(DAT)] &lt;- Demand
    TMP &lt;- rbind(TMP, cbind(DAT[iROW,], Average, DesvEst, Max, Min, Prom60, Prom30, Prom15, Prom07))
  }
  DAT &lt;- TMP
  </code></pre>