gpt4 book ai didi

r - 如何有效地将 cumprod 应用于 tidyverse 中的所有列

转载 作者:行者123 更新时间:2023-12-02 02:27:22 24 4
gpt4 key购买 nike

我有一个大型随机矩阵(500 x 100,000 或 500 x 10,000),我想将 cumprod 应用于每一列。在 500 x 10,000 上,我的代码运行时间为 13 秒。在 500 x 100,000 上它运行 32 分钟。在 tidyverse 中,是否有比以下更有效或更好的缩放方式来执行此操作?

library(tidyverse)
library(mc2d)

n.rows = 500 #Number of times
n.cols = 100000 #Number of samples
outcomes = as_tibble(matrix(1 + ifelse(rbern(n.rows * n.cols, .5), .5, -.4),
nrow = n.rows)) %>%
modify(cumprod)

最佳答案

如果您固定了tibble 数据的行数,您实际上可以使用Reduce 来实现cumprod,这似乎是一个更快的选择

do.call(rbind, Reduce("*", asplit(df, 1), accumulate = TRUE))

基准(为此感谢@akrun's solutions)

> system.time({
+ out1 <- do.call(rbind, Reduce("*", asplit(df, 1), accumulate = TRUE))
+ })
user system elapsed
6.55 0.22 6.76

> system.time({
+ out2 <- setDT(df)[, lapply(.SD, cumprod)]
+ })
user system elapsed
44.93 0.02 45.01

> all.equal(out1, as.matrix(out2))
[1] TRUE

其中虚拟数据 df 给出为

set.seed(1)
nr <- 500
df <- as_tibble(matrix(rnorm(5e7), nr), nrow = nr)

关于r - 如何有效地将 cumprod 应用于 tidyverse 中的所有列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65450246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com