函数生成;更改其他功能的默认值(部分) [英] Function generation; change defaults of other functions (partial)
问题描述
我需要一个函数生成器,它接受另一个函数和该函数的任何参数并设置新的默认值.我认为@hadley 的 pryr::partial
就是那个神奇的功能.它完全符合我的要求,除非您无法更改新的默认值.所以在这里我可以在我的新 paste
函数中更改 sep
但不能更改 collapse = "_BAR_"
的新默认值.如何让 partial
以这种方式执行(即,默认为 collapse = "_BAR_"
但如果需要,可以将其设置为 collapse = NULL
)?如果 partial
无法做到这一点,有没有办法重写 partial
的代码来做到这一点:https://github.com/hadley/pryr/blob/master/R/partial.r
I have the need for a function generator that takes another function and any arguments of that function and sets new defaults. I thought @hadley's pryr::partial
was that magic function. It does exactly what I want except you can't then change that new default. So here I can change sep
in my new paste
function but not the new default of collapse = "_BAR_"
. How can I make partial
perform this way (i.e., default to collapse = "_BAR_"
but enable setting it to collapse = NULL
if desired)? If this is not possible with partial
is there a way to rewrite the code for partial
to do this: https://github.com/hadley/pryr/blob/master/R/partial.r
library(pryr)
.paste <- pryr::partial(paste, collapse = "_FOO_")
.paste(1:5)
.paste(1:5, LETTERS[1:5], sep="_BAR_")
.paste(1:5, collapse=NULL)
> .paste(1:5)
[1] "1_FOO_2_FOO_3_FOO_4_FOO_5"
> .paste(1:5, LETTERS[1:5], sep="_BAR_")
[1] "1_BAR_A_FOO_2_BAR_B_FOO_3_BAR_C_FOO_4_BAR_D_FOO_5_BAR_E"
> .paste(1:5, collapse=NULL)
Error in paste(collapse = "_FOO_", ...) :
formal argument "collapse" matched by multiple actual arguments
推荐答案
partial
适合修复某些参数值,但如果您想更改默认值,您可能会考虑不同的策略.这行得通
partial
is good for fixing certain parameter values, but if you want to change defaults, you might consider a different strategy. This would work
.paste <- paste
formals(.paste)$collapse <- "_FOO_"
这改变了函数的参数
args(.paste)
# function (..., sep = " ", collapse = "_FOO_")
# NULL
然后你就可以了
.paste(1:5)
# [1] "1_FOO_2_FOO_3_FOO_4_FOO_5"
.paste(1:5, LETTERS[1:5], sep="_BAR_")
# [1] "1_BAR_A_FOO_2_BAR_B_FOO_3_BAR_C_FOO_4_BAR_D_FOO_5_BAR_E"
.paste(1:5, collapse=NULL)
# [1] "1" "2" "3" "4" "5"
这篇关于函数生成;更改其他功能的默认值(部分)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!