Mar*_*keD 11 functional-programming r nested-lists
在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)
}
}
Run Code Online (Sandbox Code Playgroud)
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"
Run Code Online (Sandbox Code Playgroud)
但我无法弄清楚如何修改它,以便它适用于嵌套列表:
## 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"
Run Code Online (Sandbox Code Playgroud)
可能amazing_function是什么?我想某种递归使用substitute.list可能有效,但无法找到任何东西,因此我求助于你,互联网,寻求帮助或参考使其成功.非常感谢.
嵌套深度首次遍历嵌套列表
postwalk<-function(x,f) {
if(is.list(x)) f(lapply(x,postwalk,f)) else f(x)
}
Run Code Online (Sandbox Code Playgroud)
替换函数返回修改后的列表而不是变异
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]])
}
Run Code Online (Sandbox Code Playgroud)
例
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)))
Run Code Online (Sandbox Code Playgroud)
List of 3 $ a: chr "a2" $ b: chr "b1" $ c:List of 2 ..$ d: chr "d2" ..$ e: chr "e1"