簡體   English   中英

一個簡單的For循環以打印無限序列的部分和給出錯誤:替換的長度為零

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM