I am trying to optimize code for speed and readability for a fairly complex
function inside an MCMC sampler. As of now I have a bunch of variables inside a
function that get iteratively reset inside a loop. Something like this:
set.seed(1)
K <- 10
v1 <- rnorm(K)
v2 <- rnorm(K)
v3 <- rnorm(K)
steps <- 5
row.active <- matrix(rbinom(K*steps, 1, .7), nr = K, nc = steps)
cbind(v1,v2,v3)
for(ii in 1:steps) {
v1[row.active[,ii]] <- 2*v1[row.active[,ii]]
v2[row.active[,ii]] <- 3*v3[row.active[,ii]]^(v1[row.active[,ii]])
v3[row.active[,ii]] <- (v2[row.active[,ii]] + v3[row.active[,ii]] + 3)^2
}
cbind(v1,v2,v3)
Id like to be able to do this more succinctly with something like the
following. This would also allow me to store all the variables in a matrix,
which seems better than having so many variables (I actually have about 50).
v1 <- rnorm(K)
v2 <- rnorm(K)
v3 <- rnorm(K)
vars <- cbind(v1,v2,v3)
for(ii in 1:steps) {
vars[row.active[,ii]] <- within(vars[row.active[,ii]], {
v1 <- 2*v1
v2 <- 3*v3^v1
v3 <- (v2+v3 + 3)^2
})
}
But I get this error because with() & within() dont work on objects that
arent environments such as matrices.
> + . + Error in UseMethod("within") :
no applicable method for 'within' applied to an object of class "c('double',
'numeric)"
Its important that I keep this as a matrix and not a data.frame or list
because Im trying to optimize for speed. Help is much appreciated. Thanks!
Steve
Steve Bellan, PhD, MPH
Post-doctoral Researcher
Lauren Ancel Meyers Research Group
Center for Computational Biology and Bioinformatics
University of Texas at Austin
http://www.bio.utexas.edu/research/meyers/steve_bellan/
[[alternative HTML version deleted]]
______________________________________________
[email protected] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.