Large loops hang in R? -


Suppose I want to do a simulation using the following functions:

  fn1 & Lt; - Function (n) {RES & lt; - for c () (i 1: N) {x & lt; - rnorm (2) res & lt; - c (res, x [2] -x [1])} res}  

For the large N , the countdown appears dropdown. Are there better ways to do this?

(By inspiration :)

The efficiency of the ends is essential in the work of R Those who implement tasks that essentially process the whole vector of data at once, instead of looping through them. For the loop shown above, there are two basic functions during each recurrence:

  # A random vector of two random numbers is generated; - rnorm (2) # The difference between those numbers is calculated by x [2] - x [1]  

In this case, the appropriate action will be sapply () . sapply () operates on the list of objects, such as the vector generated by the loop statement 1: N and gives a vector of result:

 < Code> sapply (1: n, function (i) {x  

note That index value is available during the i function call and takes values ​​between 1 and N respectively, though in this case its is not needed .

can be used for , where entering the habit of recognizing is a very valuable skill - several R library plug-ins for parallel calculation, And using the Apply functions Apply can often allow significant performance increases on multicore systems with refactoring of zero of code.


Comments

Popular posts from this blog

c# - ListView onScroll event -

PHP - get image from byte array -

Linux Terminal Problem with Non-Canonical Terminal I/O app -