You seem to be looking for a way to do recursive calculations in R. Base R has two ways to do this, which differ in the form of the function used for recursion. Both methods can be used for your example.
Reduce
can be used with recurrence equations of the form v[i+1] = function(v[i], x[i])
, where v
is the computed vector and x
input vector; those. when the output i+1
depends only on the i-th value of the calculated and input vectors, and the calculation performed using function(v, x)
can be non-linear. It will be for you
value <- 100 nout <- 10 # v[i+1] = function(v[i], x[i]) v <- Reduce(function(v, x) .9*v + 9, x=numeric(nout), init=value, accumulate=TRUE) cbind(step = 0:nout, v)
filter
used with recurrence equations of the form y[i+1] = x[i] + filter[1]*y[i-1] + ... + filter[p]*y[ip]
, where y
is the calculated vector and x
input vector; that is, when the output can depend linearly on the delayed values ββof the calculated vector, as well as on the i-th
value of the input vector. For your case it will be:
value <- 100 nout <- 10 # y[i+1] = x[i] + filter[1]*y[i-1] + ... + filter[p]*y[ip] y <- c(value, stats::filter(x=rep(9, nout), filter=.9, method="recursive", sides=1, init=value)) cbind(step = 0:nout, y)
For both functions, the output length is determined by the length of the input vector x
.
Both of these approaches give your result.
Walts source share