R: how do you merge/combine two environments?

前端 未结 3 1360
[愿得一人]
[愿得一人] 2021-02-18 23:01

This is a simple question but the answer is apparently not so simple... Is it possible to combine environments in R?

E1 = new.env()
E2 = new.env()
E1$x = 25
E2$y         


        
3条回答
  •  佛祖请我去吃肉
    2021-02-18 23:34

    I made this function:

    > appendEnv = function(e1, e2) {
    +     e1name = deparse(substitute(e1))
    +     e2name = deparse(substitute(e2))
    +     listE1 = ls(e1)
    +     listE2 = ls(e2)
    +     for(v in listE2) {
    +         if(v %in% listE1) warning(sprintf("Variable %s is in e1, too!", v))
    +         e1[[v]] = e2[[v]]
    +     }
    + }
    
    > e1 = new.env()
    > e2 = new.env()
    > e1$x = 1
    > e1$y = 2
    > e2$y = 3
    > e2$z = 4
    > appendEnv(e1, e2)
    Warning message:
    In appendEnv(e1, e2) : Variable y is in e1, too!
    > as.list(e1)
    $x
    [1] 1
    
    $y
    [1] 3
    
    $z
    [1] 4
    

提交回复
热议问题