Search code examples
rfor-loopiterationinfinite-sequence

A simple For loop to print partial sums of infinite sequence gives error: replacement has length zero


A simple problem in R using the For loop to compute partial sums of an infinite sequence is running into an error.

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

Error in b[t] <- b[t - 1] + a[t] : replacement has length zero


Solution

  • A great deal of power of R comes from vectorization. Here there is no need of for loops. You can apply your formula directly on t (the vector of input values). Then notice that b is the cumulative sum of a.

    Just try:

    t <- 1:20
    a <- ((-1)^(t-1))/(t)
    b <- cumsum(a)