Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用purrr::reduce()进行迭代_R_Reduce_Purrr - Fatal编程技术网

使用purrr::reduce()进行迭代

使用purrr::reduce()进行迭代,r,reduce,purrr,R,Reduce,Purrr,给定一个初始值为a=3的函数f(a,x)=a*x,假设在下一步中有一个迭代,其中a被赋值为f(a,x) 对于x=2,a分配f(3,x=2)=6,然后 对于x=3,a分配f(6,x=3)=18,然后 对于x=4,a分配f(18,x=4)=72 如何使用purr实现迭代?下面的说法并不完全正确 库(purrr) a[1]18 2:4%>%累积(~f(a,)) #> [1] 2 6 18 由(v0.3.0)于2020年4月24日创建 2:4 %>% accumulate(~f(.y,

给定一个初始值为
a=3
的函数
f(a,x)=a*x
,假设在下一步中有一个迭代,其中
a
被赋值为
f(a,x)

  • 对于
    x=2
    a
    分配
    f(3,x=2)=6
    ,然后
  • 对于
    x=3
    a
    分配
    f(6,x=3)=18
    ,然后
  • 对于
    x=4
    a
    分配
    f(18,x=4)=72
如何使用
purr
实现迭代?下面的说法并不完全正确

库(purrr)
a[1]18
2:4%>%累积(~f(a,))
#> [1]  2  6 18

由(v0.3.0)于2020年4月24日创建

2:4 %>% accumulate(~f(.y, .x), .init=3)
# [1]  3  6 18 72

.x
值表示上一个值,而
.y
以下是要导入的向量中的下一个元素。我们不是在函数中硬编码
a=3
,而是通过
.init=
传递给它,它只在第一次迭代时发生。

在base R中,您可以使用
Reduce
accumulate=TRUE

Reduce(f, 2:4, init = 3, accumulate = TRUE)
#[1]  3  6 18 72