我正在详细写 purrr 的累积函数,并且在大多数情况下,当
.dir
设置为“向前”时,我了解其机制,但是当我将 .dir
设置为“向后”时,我变得不-直观的结果。
以下是.dir设置为“forward”时对accumulate的理解:
使用accumulate时,
.x
参数通过'...'(或者可能是第二个命名参数)传递到你的函数体的函数,并且函数体的输出通过a作为迭代输入传递到你的函数命名参数(比如“x”)
下面是我如何仅使用 purrr 函数的一个输入(迭代部分并忽略 .x 作为输入)的示例
library(tidyverse)
accumulate(
.x= 20:25 # this gets passed through to the body's function via `...`
,.f = function(x,...){
print(paste0("... is: ",...)) # this will print the .x args sequentially
print(paste0("x is: ",x)) # this will print the .init command then function's body recursive input
sum(x,1) # this function that will start with the previous output (or .init) and iteratively repeat (ignoring .x)
}
,.init = 0 #the initial input to iterative function
,.dir = "forward"
)
运行此代码时,我们验证了上面的理解,该函数以 0 开头(从 0 的 .init arg 开始),然后依次增加 1 并忽略 .x 输入(仅在打印命令中使用它们)
当我们保留相同的功能并将
.dir
更改为“向后”时,就会出现混乱。
# comments are relative to what happens when .dir is set to forward
accumulate(
.x= 20:25 # this gets passed through to the function via `...`
,.f = function(x,...){
print(paste0("... is: ",...)) # this will print the .x args sequentially
print(paste0("x is: ",x)) # this will print the .init command then recursive
sum(x,1) this function that will start with the previous output (or .init) and iteratively repeat (ignoring .x)
}
,.init = 0 #the initial input to iterative function
,.dir = "backward"
)
从上面来看,我希望忽略“.x”参数,而只有函数之前的输入流过函数体。
相反,.x 参数通过名为“x”变量传递到函数体,而“...”参数被忽略(与上面相反)
思考为什么争论会发生转变?理解重要吗?或者从从业者的角度来看,当 .dir 设置为向后时,我可以只注意到输入逻辑切换吗?
经过进一步调查,当您将 .dir 参数设置为“向后”时,它会翻转函数体内 .x 和 ... 的顺序。
其他都一样,你只需要记住交换它们即可。