Skip to content
Prev 206736 / 398503 Next

Odp: For loops in R

Hello Petr.

For the random values, I wanted to generate a different random number for
each element of my velocity matrix.

So will this do it?

rmat <- matrix(runif(1000), 500,2)
rmat2 <- matrix(runif(1000), 500,2)
rindex <- sample(1:500, replace=TRUE) #with repetition
velocity<-0.4 * velocity + rmat * (pbestsVar - popVar) + rmat2 *
(archiveVar[rindex,] - popVar)

Also, do the apply methods perform better than for loops given the same
function?
sample:
apply(x, fun) 
and 
for (i in 1:length(x)) fun(x[i])

cheers
cjmr