-1

I have following R code:

>a
 1
 2
 3
 4
 5

I want to create b such that b[i] = a[i] + b[i-1].

Need help, how to do above action in R.

RHelp
  • 815
  • 2
  • 8
  • 23

2 Answers2

0
b <- cumsum(b) + a

wil do the trick.

Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
0

Like this?

Rgames> a <- 1:5
Rgames> b<-rep(7,5)
Rgames> b[-1]<-b[1:(length(b)-1)]+a[1:(length(a)-1)]
Rgames> b
[1]  7  8  9 10 11

You haven't stated whether you expect to add the updated value of b[j-1] to the new value of b[j] .

Carl Witthoft
  • 20,573
  • 9
  • 43
  • 73