In R, I'm trying to create a way to transform function parameters given in ...
to values in a pre-determined list within a closure function.
I would like to be able to do something like this:
function_generator <- function(args_list = list(a = "a",
b = "b",
c = list(d = "d",
e = "e")){
g <- function(...){
## ... will have same names as args list
## e.g. a = "changed_a", d = "changed_d"
## if absent, then args_list stays the same e.g. b="b", e="e"
arguments <- list(...)
modified_args_list <- amazing_function(arguments, args_list)
return(modified_args_list)
}
}
args_list
will be different each time - its a body object to be sent in a httr
request.
I've got a function that works if the list does not have nested lists:
substitute.list <- function(template, replace_me){
template[names(replace_me)] <-
replace_me[intersect(names(template),names(replace_me))]
return(template)
}
t <- list(a = "a", b="b", c="c")
s <- list(a = "changed_a", c = "changed_c")
substitute.list(t, s)
> $a
>[1] "changed_a"
>$b
>[1] "b"
>$c
>[1] "changed_c"
But I can't work out how to modify it so that it works with nested lists:
## desired output
t <- list(a = "a", b = "b", c = list(d = "d", e = "e"))
s <- list(a = "changed_a", d = "changed_d")
str(t)
List of 3
$ a: chr "a1"
$ b: chr "b1"
$ c:List of 2
..$ d: chr "d1"
..$ e: chr "e1"
amaze <- amazing_function(t, s)
str(amaze)
List of 3
$ a: chr "changed_a"
$ b: chr "b1"
$ c:List of 2
..$ d: chr "changed_d"
..$ e: chr "e1"
What could amazing_function
be? I guess some kind of recursion using substitute.list
could work, but haven't been able to find anything, hence I turn to you, internet, for help or references to make it work.
Much obliged.