r - 打印无限序列部分和的简单 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] 中的错误:替换的长度为零
解决方案
两个变化:-
for
1)在循环中使用不同的变量
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 中的一个函数
推荐阅读
- ios - Swift 和 Firebase 首先将驱动程序整理成一个数组
- npm - 确保 package-lock.json 为依赖项的要求保留特定版本
- java - Collections.reverse 无法正常工作
- lua - Lua 性能损失 - 清除表
- javascript - How do I convert a remote JSON object to an Array in JavaScript
- react-native - 未定义不是对象 -> 反应原生 JS
- javascript - Typescript: declare empty class object
- amazon-web-services - AWS - WebSockets 未通过 HTTPS 连接
- ruby-on-rails - In Ruby, how does one verify the identity of a Struct?
- asp.net-core - 使用 UNIX 套接字升级到 ASP.NET Core 2.1 的问题