如何直接在purrr :: accumulate2()内部编写自定义函数 [英] How to write a custom function directly inside purrr::accumulate2()
问题描述
我只是尝试使用purrr家族的lambda函数.
I am just trying my hands on lambda functions of purrr family.
假设我必须通过 accumulate
对向量中先前迭代的结果进行迭代操作,可以通过.x和.y进行,其中.x是对先前元素和应用的结果.y是当前元素.还要假设函数/迭代次数是 2x + 3y
,即将先前的结果加倍并添加当前元素的三倍,可以通过like来完成.
Suppose I have to do some operation iteratively over result of previous iteration in vector through accumulate
I can do it through .x and .y, where .x is result of application on previous element and .y is current element. Also assume that the function/iteration is 2x+3y
i.e. double the previous result and add three times of current element, it can be done through like.
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
OR
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()
是一个三参数函数,其中第一个参数是先前计算的结果,而其他两个参数则直接传递.
What actually I understood from purrr::accumulate()
was that, it is a two argument function where first argument is result of previous iteration and second argument is vector passed into it directly. On similar lines accumulate2()
is a three argument function where first argument is result of previous computation and other two arguments are passed directly.
有人可以说出我在理解逻辑上错了什么地方或哪里错了,或者什么是正确的做事方式.
Can someone tell where I am erring or am wrong in understanding the logic or what should be the correct way of doing it.
推荐答案
仅当有两个参数时,才指定 .x
和 .y
.超过2个时,我们可以按出现的顺序使用 .. 1
, .. 2
, .. 3
The .x
and .y
are only specified when there are two arguments. With more than 2, we can use ..1
, ..2
, ..3
in their order of occurrence
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
这篇关于如何直接在purrr :: accumulate2()内部编写自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!