when do you want to set up new environments in R

后端 未结 3 1216
故里飘歌
故里飘歌 2021-02-19 00:27

per the discussion of R programming styles, I saw someone once said he puts all his custom function into a new environment and attach it. I also remember R environment maybe use

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-19 00:47

    Martin Mächler suggests that this is the one time you might want to consider attach(), although he suggested it in the context of attaching a .Rdata file to the search path but your Q is essentially the same thing.

    The advantage is that you don't clutter the global environment with functions, that might get overwritten accidentally etc. Whilst I wouldn't go so far as to call this bad style, you might be better off sticking your custom functions into your own personal R package. Yes, this will incur a bit of overhead of setting up the package structure and providing some documentation to allow the package to be installed, but in the longer term this is a better solution. With tools like roxygen this process is getting easier to boot.

    Personally, I haven't found a need for fiddling with environments in 10+ years of using R; well documented scripts that load, process and analyse data, cleaning up after themselves all the while have served me well thus far.


    Another suggestion for the second part of your question (now deleted) is to use with() (following on from @Joshua's example):

    > .myEnv <- new.env()
    > .myEnv$a <- 2
    > a <- 1
    > str(a)
     num 1
    > ls.str(.myEnv, a)
    a :  num 2
    > str(.myEnv$a)
     num 2
    > with(.myEnv, a)
    [1] 2
    > a
    [1] 1
    

提交回复
热议问题