R中累加和的向量 [英] Vector of cumulative sums in R
本文介绍了R中累加和的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试获得一个累加和的向量,也就是说,我有:
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])
}
最后一行代码是问题,我希望'I'是一个向量,使得I [1] = F [1],I [n] = F [1] + F [2] +.... + F [n].出于某些原因,cumsum函数无法正常工作.尝试这样做有什么问题?
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 ?
推荐答案
如果我有误解,请纠正我,但我相信你只是想要这样做:
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.
这篇关于R中累加和的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文