gpt4 book ai didi

r - 如何直接在 purrr::accumulate2() 中编写自定义函数

转载 作者:行者123 更新时间:2023-12-04 12:34:03 25 4
gpt4 key购买 nike

我只是在尝试 purrr 系列的 lambda 函数。

假设我必须通过 accumulate 对 vector 中先前迭代的结果进行一些迭代操作,我可以通过 .x 和 .y 来完成,其中 .x 是结果前一个元素上的应用程序和 .y 是当前元素。还假设函数/迭代是 2x+3y,即将之前的结果加倍并添加当前元素的三倍,它可以通过类似的方式完成。

accumulate(1:10, ~2*.x + 3*.y)
[1] 1 8 25 62 139 296 613 1250 2527 5084

#OR
accumulate(1:10, ~2*.x + 3*.y, .init = 2.5)
[1] 2.5 8.0 22.0 53.0 118.0 251.0 520.0 1061.0 2146.0 4319.0 8668.0

但是,我无法在 accumulate2

中执行这些类型的迭代
accumulate2(1:5, 1:5, ~2*.x + 3*.y +.z)
Error in reduce2_impl(.x, .y, .f, ..., .init = .init, .acc = TRUE) :
`.y` does not have length 4

accumulate2(1:5, 1:4, ~2*.x + 3*.y +.z)
Error in .f(out, .x[[x_i]], .y[[y_i]], ...) : object '.z' not found

实际上我从 purrr::accumulate 中了解到,它是一个双参数函数,其中第一个参数是前一次迭代的结果,第二个参数是直接传递给它的向量。在类似的行上,accumulate2 是一个三参数函数,其中第一个参数是先前计算的结果,其他两个参数直接传递。

谁能告诉我我在理解逻辑上哪里犯了错误或错误,或者正确的做法应该是什么。

最佳答案

.x.y 仅在有两个参数时指定。如果大于 2,我们可以按出现顺序使用 ..1..2..3

library(purrr)
accumulate2(1:5, 1:4, ~2*..1 + 3*..2 +..3)
#[[1]]
#[1] 1

#[[2]]
#[1] 9

#[[3]]
#[1] 29

#[[4]]
#[1] 73

#[[5]]
#[1] 165

关于r - 如何直接在 purrr::accumulate2() 中编写自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66423010/

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