如何直接在 purrr::accumulate2() 中编写自定义函数 [英] How to write a custom function directly inside purrr::accumulate2()

查看:32
本文介绍了如何直接在 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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆