r - Function generation; change defaults of other functions (partial) -
i have need function generator takes function , arguments of function , sets new defaults. thought @hadley's pryr::partial magic function. want except can't change new default. here can change sep in new paste function not new default of collapse = "_bar_". how can make partial perform way (i.e., default collapse = "_bar_" enable setting collapse = null if desired)? if not possible partial there way rewrite code partial 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 multiple actual arguments
partial fixing parameter values, if want change defaults, might consider different strategy. work
.paste <- paste formals(.paste)$collapse <- "_foo_" this changes parameters function
args(.paste) # function (..., sep = " ", collapse = "_foo_") # null then can do
.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"
Comments
Post a Comment