大循环挂在R? [英] Large loops hang in R?

查看:129
本文介绍了大循环挂在R?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想用下面的函数执行一个模拟:

 x<  -  r norm(2)
res(-b),函数(N){
res& < -c(res,x [2] -x [1])$ ​​b $ b}
res
}

对于非常大的 N ,计算似乎挂起。有没有更好的方法来做到这一点?



(受启发: https://stat.ethz.ch/pipermail/r-help/2008-February/155591.html


<解决方案

在R中的循环出了名的缓慢,但这里还有另一个问题。在每个迭代中预先分配结果向量res,而是附加到res。



下面我们可以比较上面版本的速度和简单启动的版本(n),并且在循环期间改变第i个元素。

  fn1 < -  function(N)对于(i,1:N){
x -norm(2)
res< -c(res,x [ 2] -x [1])$ ​​b $ b}
res
}
fn2 < - function(N){
res < - rep(0,N)
(i in 1:N){
x < - rnorm(2)
res [i] < - x [2] -x [1]
}
res
}
> N< - 50000
> system.time(res1 <-fn1(N))
用户系统经过
6.568 0.256 6.826
> system.time(res2 <-fn2(N))
用户系统已用
0.452 0.004 0.496

另外,正如Sharpie指出的那样,可以通过使用R函数(如 apply )(或其亲属, sapply (b)

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ :N,function(i){x < - rnorm(2); return(x [2] -x [1])})
}
> system.time(res3 <-fn3(N))
用户系统流逝的
0.397 0.004 0.397


Suppose I want perform a simulation using the following function:

fn1 <- function(N) {
  res <- c()
  for (i in 1:N) {
    x <- rnorm(2)
    res <- c(res, x[2]-x[1])
  }
  res
}

For very large N, computation appears to hang. Are there better ways of doing this?

(Inspired by: https://stat.ethz.ch/pipermail/r-help/2008-February/155591.html)

解决方案

For loops in R are notoriously slow, but here there's another issue. It's much faster to preallocate the results vector, res, rather append to res at each iteration.

Below we can compare the speed of the above version with a version that simply starts with a vector, res, of length N and changes the ith element during the loop.

fn1 <- function(N) {
  res <- c()
  for (i in 1:N) {
     x <- rnorm(2)
     res <- c(res,x[2]-x[1])
  }
  res
}
fn2 <- function(N) {
  res <- rep(0,N)
  for (i in 1:N) {
     x <- rnorm(2)
     res[i] <- x[2]-x[1]
  }
  res
}
> N <- 50000
> system.time(res1 <- fn1(N))
   user  system elapsed 
  6.568   0.256   6.826 
> system.time(res2 <- fn2(N))
   user  system elapsed 
  0.452   0.004   0.496 

Also, as Sharpie points out, we can make this slightly faster by using R functions like apply (or its relatives, sapply and lapply).

fn3 <- function(N) {
  sapply( 1:N, function( i ){ x <- rnorm(2); return( x[2] - x[1] ) } )
}
> system.time(res3 <- fn3(N))
   user  system elapsed 
  0.397   0.004   0.397 

这篇关于大循环挂在R?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆