向量化这个 for 循环(当前行取决于上面的行)
假设我想在给定预生成的正/负矩阵 (100x3) 的情况下创建 n=3 条随机游走路径(路径长度 = 100)。第一条路径将从 10 开始,第二条路径从 20 开始,第三条路径从 30 开始:
设置.seed(123)
给定.rand.matrix <- 复制(3,sign(rnorm(100)))
路径 <- 矩阵(NA,101,3)
路径[1,] = c(10,20,30)
for (j in 2:101) {
路径[j,]<-路径[j-1,]+given.rand.matrix[j-1,]
}
最终值(给定种子和兰特矩阵)是 14, 6, 34...这是期望的结果...但是...
问题:有没有办法向量化 for 循环?问题在于计算时路径矩阵尚未完全填充。因此,将循环替换为 <代码> 路径[2:101,]<-路径[1:100,]+given.rand.matrix 返回的大部分是 NA。我只是想知道这种类型的 for 循环在 R 中是否可以避免。
提前非常感谢。
Suppose I want to create n=3 random walk paths (pathlength = 100) given a pre-generated matrix (100x3) of plus/minus ones. The first path will start at 10, the second at 20, the third at 30:
set.seed(123)
given.rand.matrix <- replicate(3,sign(rnorm(100)))
path <- matrix(NA,101,3)
path[1,] = c(10,20,30)
for (j in 2:101) {
path[j,]<-path[j-1,]+given.rand.matrix[j-1,]
}
The end values (given the seed and rand matrix) are 14, 6, 34... which is the desired result... but...
Question: Is there a way to vectorize the for loop? The problem is that the path matrix is not yet fully populated when calculating. Thus, replacing the loop with
path[2:101,]<-path[1:100,]+given.rand.matrix
returns mostly NAs. I just want to know if this type of for loop is avoidable in R.
Thank you very much in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
绝对可向量化:跳过
path
的初始化,并在矩阵上使用cumsum
:Definitely vectorizable: Skip the initialization of
path
, and usecumsum
over the matrix: