Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 205278

Loop calculation with previous value not using for in R

$
0
0

I'm a beginning R programmer. I have trouble in a loop calculation with a previous value like recursion. An example of my data:

 dt <- data.table(a = c(0:4), b = c( 0, 1, 2, 1, 3))

And calculated value 'c' is y[n] = (y[n-1] + b[n])*a[n]. Initial value of c is 0. (c[1] = 0)

I used the for loop and the code and result is as below.

dt$y <- 0
for (i in 2:nrow(dt)) {
  dt$y[i] <- (dt$y[i - 1] + dt$b[i]) * dt$a[i]
}

   a b  y
1: 0 0  0
2: 1 1  1
3: 2 2  6
4: 3 1 21
5: 4 3 96

This result is what I want. However, my data has over 1,000,000 rows and several columns, therefore I'm trying to find other ways without using a for loop. I tried to use "Reduce()", but it only works with a single vector (ex. y[n] = y_[n-1]+b[n]). As shown above, my function uses two vectors, a and b, so I can't find a solution.

Is there a more efficient way to be faster without using a for loop, such as using a recursive function or any good package functions?


Viewing all articles
Browse latest Browse all 205278

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>