1

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

jogo
  • 12,469
  • 11
  • 37
  • 42

2 Answers2

1

Two changes :-

1) Use different variable in for loop

2) Don't use seq_along since t has already the index on which you want to iterate

for (i in t){  
  a[i] = ((-1)^(i-1))/(i) # some formula
  b[i] = b[i-1]+a[i]        
}

Also t is not a good variable name since it is a function in R

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

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)
nicola
  • 24,005
  • 3
  • 35
  • 56