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.
Post-order depth first walk of nested list
postwalk<-function(x,f) {
if(is.list(x)) f(lapply(x,postwalk,f)) else f(x)
}
Replacement function that returns modified list rather than mutating in place
replace.kv<-function(x,m) {
if(!is.list(x)) return(x)
i<-match(names(x),names(m));
w<-which(!is.na(i));
replace(x,w,m[i[w]])
}
Example
t<-list(a="a1", b="b1", c=list(d="d1", e="e1"))
s<-list(a="a2", d="d2")
str(postwalk(t,function(x) replace.kv(x,s)))
List of 3 $ a: chr "a2" $ b: chr "b1" $ c:List of 2 ..$ d: chr "d2" ..$ e: chr "e1"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With