更新时间:2023-11-28 23:25:22
嵌套列表的后深度深度第一步
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]])
}
示例
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"