加速R中包含和的for循环

加速R中包含和的for循环,r,for-loop,R,For Loop,我想知道是否有可能修改这个循环以运行得更快。当我以n=2000000运行它时,大约需要25秒。有什么窍门吗 for(i in 1:n) { x[i] <- sum(runif(20)) } for(1:n中的i) { 使用apply可以让你的速度有所提高 # How many rows? n <- 1000 # How many samples from runif? k <- 20 # Preallocate x x <- double(n) ## Your

我想知道是否有可能修改这个循环以运行得更快。当我以n=2000000运行它时,大约需要25秒。有什么窍门吗

for(i in 1:n)
{
    x[i] <- sum(runif(20))
}
for(1:n中的i)
{

使用apply可以让你的速度有所提高

# How many rows?
n <- 1000
# How many samples from runif?
k <- 20
# Preallocate x
x <- double(n)

## Your loop
for(i in 1:n){
  x[i] <- sum(runif(k))
}

## Using apply
## First create a matrix that has n rows and k columns
## then find the sum of the row.
x <- apply(matrix(runif(n*k), nrow=n), 1, sum)
#有多少行?

n
system.time(x我更喜欢以下解决方案:

x <- rep(sum(runif(20)), 2e6)

x是否已经预分配了x?你应该发布你正在做的事情的完整代码。是的,最好为结果对象
x
预分配内存。这里有很多技巧,需要做一些小的修改:
n
system.time(x <- rowSums(matrix(runif(2e6),ncol=20)))
#   user  system elapsed 
#  0.108   0.620   0.748 
x <- rep(sum(runif(20)), 2e6)