Use … to modify a nested list within a functional

前端 未结 1 1772
谎友^
谎友^ 2021-02-20 09:20

In R, I\'m trying to create a way to transform function parameters given in ... to values in a pre-determined list within a closure function.

I would like t

相关标签:
1条回答
  • 2021-02-20 10:03

    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"
    
    0 讨论(0)
提交回复
热议问题