Created
January 17, 2023 19:44
-
-
Save dmi3kno/f44f72d571246b7c09247e8a5699a535 to your computer and use it in GitHub Desktop.
Function factory with changeable argument name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(magrittr) | |
logit <- function(u) log(u)-log(1-u) | |
raise_to_pow <- function(fun, pname_pow=".pow"){ | |
eval(parse(text=gsub(pattern=".pow", replacement=pname_pow, | |
"function(u, .pow=1, ...) fun(u,...)^(.pow)"))) | |
} | |
powlogit <- logit %>% raise_to_pow(pname_pow="e") | |
powlogit(0.2,e=2) | |
#[1] 1.921812 | |
logit(0.2)^2 | |
#[1] 1.921812 |
I think the bquote
is the least transparent solution. The explicit call construction with do.call
has a slight benchmark advantage, so I reused it and expanded for readability (at negligible cost).
raise_to_pow4 <- function(fun, pname_pow=".pow") {
f <- function(u, .pow=1, ...){
fun(u,...)^(.pow)
}
formals_ <- formals(f)
body_ <- body(f)
names(formals_)[names(formals_) == ".pow"] <- pname_pow
body_ <- do.call(substitute, list(body_, list(.pow = as.symbol(pname_pow))))
as.function(c(formals_, body_))
}
Now I can separate the programming from meta-programming and refactor my functions easily. Thank you very much @moodymudskipper for this!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here are 3 options: