向量化这个 for 循环(当前行取决于上面的行)

发布于 2024-10-14 05:25:07 字数 597 浏览 6 评论 0原文

假设我想在给定预生成的正/负矩阵 (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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

音盲 2024-10-21 05:25:07

绝对可向量化:跳过 path 的初始化,并在矩阵上使用 cumsum

path <- apply( rbind(c(10,20,30),given.rand.matrix), 2, cumsum)

> head(path)
     [,1] [,2] [,3]
[1,]   10   20   30
[2,]    9   19   31
[3,]    8   20   32
[4,]    9   19   31
[5,]   10   18   32
[6,]   11   17   31
> tail(path)
       [,1] [,2] [,3]
[96,]    15    7   31
[97,]    14    8   32
[98,]    15    9   33
[99,]    16    8   32
[100,]   15    7   33
[101,]   14    6   34

Definitely vectorizable: Skip the initialization of path, and use cumsum over the matrix:

path <- apply( rbind(c(10,20,30),given.rand.matrix), 2, cumsum)

> head(path)
     [,1] [,2] [,3]
[1,]   10   20   30
[2,]    9   19   31
[3,]    8   20   32
[4,]    9   19   31
[5,]   10   18   32
[6,]   11   17   31
> tail(path)
       [,1] [,2] [,3]
[96,]    15    7   31
[97,]    14    8   32
[98,]    15    9   33
[99,]    16    8   32
[100,]   15    7   33
[101,]   14    6   34
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文