Vector of cumulative sums in R

大憨熊 提交于 2019-11-27 19:35:13

问题


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:


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.



来源:https://stackoverflow.com/questions/30423496/vector-of-cumulative-sums-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!