首页 > 解决方案 > 打印无限序列部分和的简单 For 循环给出错误:替换长度为零

问题描述

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] 中的错误:替换的长度为零

标签: rfor-loopiterationinfinite-sequence

解决方案


两个变化:-

for1)在循环中使用不同的变量

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 中的一个函数


推荐阅读