gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:14:56 25 4
gpt4 key购买 nike

在 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 进行某种递归可以工作,但一直找不到任何东西,因此我转向你,互联网,寻求帮助或引用以使其工作。
多谢。

最佳答案

嵌套列表的后序深度优先遍历

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

返回修改后的列表而不是原地变异的替换函数
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)))

3人名单
$ a: chr "a2"
$ b: chr "b1"
$ c:列表 2
..$ d: chr "d2"
..$ e: chr "e1"

关于r - 使用 ... 修改函数中的嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31950336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com