使用 ... 修改函数中的嵌套列表

Use ... to modify a nested list within a functional

在 R 中,我正在尝试创建一种方法,将 ... 中给出的函数参数转换为闭包函数中预先确定的列表中的值。

我希望能够做这样的事情:

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每次都会不同 - 它是在 httr 请求中发送的正文对象。

如果列表没有嵌套列表,我有一个函数可以工作:

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"

但我不知道如何修改它以使其适用于嵌套列表:

## 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"

amazing_function会是什么?我想使用 substitute.list 的某种递归可能会起作用,但一直无法找到任何东西,因此我向您求助,互联网,寻求帮助或参考以使其起作用。 非常感谢。

Post-嵌套列表的顺序深度优先

postwalk<-function(x,f) {
  if(is.list(x)) f(lapply(x,postwalk,f))  else f(x)
}

returns 修改列表而不是就地变异的替换函数

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]])
}

示例

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"