Use … to modify a nested list within a functional

徘徊边缘 提交于 2019-12-03 11:26:38

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"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!