Hi

r-help-boun...@r-project.org napsal dne 19.01.2010 02:32:45:

> 
> 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)

AFAICS it seems to do what you want. Basically your rmat and rmat2 will 
have different numbers from uniform distribution. If you wanted different 
distribution of random numbers you need to use differend random number 
generator. See ?rnorm.

And repetition means that in your index you can have some rows more times 
and some rows never. Again only you know if this is desired behaviour. If 
not use replace=FALSE.

> 
> 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])

In some quite recent R-News (I believe 2009 or 2008) there is an article 
about loops. And also R-Inferno by P.Burns is worth reading.

My opinion is that simple cycles and apply functions are more or less 
similar. When I want to scan a file and make same plots for each column I 
use for cycle and in most other cases I use *apply family. If you have 
nested cycles which work correctly in reasonable time why not use them. 
But usually vectorised approach can be far quicker and, when you get used 
to it, clearer.

Regards
Petr


> 
> cheers
> cjmr
> 
> 
> -- 
> View this message in context: 
http://n4.nabble.com/For-loops-in-R-tp1015933p1017196.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> R-help@r-project.org 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.

______________________________________________
R-help@r-project.org 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.

Reply via email to