Vector of cumulative sums in R

2019-01-20 16:22发布

I'm trying to get a vector of cumulative sums, that is, I have:

    # 500 Samples from the U(0,1) Distribution
U<-runif(500,0,1)

# Empty Vector of length 500
F<-rep(0,500)

# Fill the vector with f(U(k))
for ( i in 1:500 ){
  F[i] <- sqrt(1-U[i]^2)
}

# Another Empty Vector of length 500
I<-rep(0,500)

# Fill the second empty vector with the sums of F
for ( i in 1:500 ){
  I[i]<-cumsum(F[1]:F[i])
}

The last line of code is the problem, I want 'I' to be a vector such that I[1] = F[1], I[n] = F[1] + F[2] +.....+ F[n]. The cumsum function doesn't work for this for some reason. What is wrong with trying to do it like this ?

1条回答
The star\"
2楼-- · 2019-01-20 16:57

Please correct me if I'm misunderstanding, but I believe you simply want this:

I <- cumsum(sqrt(1 - U^2))

It is unclear why you want to use for loops.

查看更多
登录 后发表回答