0

i want to calculate cumulative loss at each set of iterations. i.e. let's say my n_sim <-1000 and x=rep(3,n_sim).

in the above case, set of iteration is 3 and number of set of iteration is 1000, so total 3000 (1000*3) iterations. Let's define below: Iter <- rep(1:n_sim, x), Val <-rnorm(3*n_sim), df<-data.frame(Iter,Val).

problem:i want to calculate sum of Val taking each set of iteration meaning as here a set consist of 3 iterations, i want to take Val of first 3 iterations and calculate sum and so on. So i will have a final vector of length 1000 containing sum of Val of each set.

I have tried below using for loops, but it is very very slow while doing 1mn simulations.

sum_value <-array(0,c(n_sim)) for(i in 1: n_sim) { sum_value[i] = df[df$Iter==i,] %>% .$Val %>% sum } Anyone has better idea how to fast this process.

Narendra Sahu
  • 136
  • 2
  • 14
  • 2
    `colSums(matrix(DF$Val, nrow = 3))`? – Roland Nov 22 '19 at 12:15
  • Thanks Roland for quick reply. for this example it may work taking ```nrow=3````. However i am looking at dynamic nrow. it may be of multiple values as well. For e.g instead of setting this set of iteration to constant 3, it may vary i.e. some set may contain 3 iterations, some may contain 4 and so on. – Narendra Sahu Nov 22 '19 at 12:23
  • Thank you Roland. `aggregate` does the job very fast. – Narendra Sahu Nov 22 '19 at 12:56
  • Fast is relative. `aggregate` is actually quite slow. – Roland Nov 22 '19 at 13:07

0 Answers0