[R] do.call or something instead of for
Petr Savicky
savicky at cs.cas.cz
Mon Jun 25 15:37:20 CEST 2012
On Mon, Jun 25, 2012 at 05:39:45AM -0700, Kathie wrote:
> Dear R users,
>
> I'd like to compute X like below.
>
> X_{i,t} = 0.1*t + 2*X_{i,t-1} + W_{i,t}
>
> where W_{i,t} are from Uniform(0,2) and X_{i,0} = 1+5*W_{i,0}
>
> Of course, I can do this with "for" statement, but I don't think it's good
> idea because "i" and "t" are too big.
>
> So, my question is that
>
> Is there any better idea to avoid "for" statement for this problem?
Hi.
The recurrence does not use index i. So, it is possible to vectorize
over i. Try the following.
m <- 10 # bound on i
n <- 6 # bound on tt
W <- matrix(runif(m*n, max=2), nrow=m, ncol=n)
X <- matrix(nrow=m, ncol=n)
X[, 1] <- 1 + 5*W[, 1]
for (tt in seq.int(from=2, length=n-1)) {
X[, tt] <- 0.1*(tt-1) + 2*X[, tt-1] + W[, tt]
}
The code uses tt instead of t to avoid confusion with the transpose function.
If n is always at least 2, then seq.int(from=2, length=n-1) may be
replaced by 2:n.
Hope this helps.
Petr Savicky.
More information about the R-help
mailing list