[R] Adjusting values via vectorization

Albert Vernon Smith avsmith at gmail.com
Tue Mar 1 19:10:41 CET 2011


I'm adjusting values in a list based on a couple of matrixes.  One matrix specifies the row to be taken from the adjustment matrix, while using the aligned column values.  I have an approach which works, but I might find an approach with vectorization. 

Here is code with my solution:

--
nids <- 10
npredictors <- 2
ncol <- 4
values <- sample(c(-1,0,1),nids,replace=TRUE)
input <- matrix(sample(1:ncol,nids*npredictors,replace=TRUE),nrow=nids)
values.adjust <- matrix(rnorm(ncol*npredictors),ncol=npredictors)

for(i in 1:nids){
  for(j in 1:npredictors){
    values[i] <- values[i] + values.adjust[input[i,j],j]
  }
}
--

I'm using this as an example to hopefully better understand R syntax w.r.t. vectorization.  Is there such a way to replace my for loops?

Thanks,
-albert


More information about the R-help mailing list