[英]A simple For loop to print partial sums of infinite sequence gives error: replacement has length zero
R中使用For循環來計算無限序列的部分和的一個簡單問題遇到了錯誤。
t <- 2:20
a <- numeric(20) # first define the vector and its size
b <- numeric(20)
a[1]=1
b[1]=1
for (t in seq_along(t)){
a[t] = ((-1)^(t-1))/(t) # some formula
b[t] = b[t-1]+a[t]
}
b
b [t] <-b [t-1] + a [t]中的錯誤:替換的長度為零
兩項更改:
1)在for
循環中使用其他變量
2)不要使用seq_along
因為t
已經有要迭代的索引
for (i in t){
a[i] = ((-1)^(i-1))/(i) # some formula
b[i] = b[i-1]+a[i]
}
另外t
不是一個好的變量名,因為它是R中的函數
R的強大功能來自矢量化。 這里不需要for
循環。 您可以將公式直接應用於t
(輸入值的向量)。 然后發現, b
是累積和a
。
你試一試:
t <- 1:20
a <- ((-1)^(t-1))/(t)
b <- cumsum(a)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.