gpt4 book ai didi

R cumsum 与基于值的乘法

转载 作者:行者123 更新时间:2023-12-04 23:38:38 27 4
gpt4 key购买 nike

我有一个正数向量,使得
- 如果数字大于或等于 1,则相加
- 如果数字小于 1,则乘以累积和。

例如

> set.seed(0)
> x <- sample(c(0.9, 0.9, 0.9, 1:3), 10, replace=T)
> x
[1] 3.0 0.9 0.9 1.0 3.0 0.9 3.0 3.0 1.0 1.0

结果向量
3  2.7  2.43  3.43  6.43  5.787  8.787  11.787  12.787  13.787

有没有办法在不使用 for 循环的情况下做到这一点?

最佳答案

这是一个 tidyverse使用 purrr::accumulate 替代@G.Grothendieck 的答案:

library(tidyverse)
accumulate(x, function(x, y) if_else(y < 1, x * y, x + y))
#> [1] 3.000 2.700 2.430 3.430 6.430 5.787 8.787 11.787 12.787 13.787

关于R cumsum 与基于值的乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46459367/

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