About me | pbdR Tech | HPSC | Phyloclustering | R_note |

R_note -- The Exploration of Statistical Software R (統計軟體 R 深度歷險)
About R_note
Reference
MS Windows

Batch jobs
Function
Data/MySQL
Plot
String/Parse

Remark Lines
Classes/S3
S4 Methods
Batch more
Environment

Good Coding
Fast Loop
LAM/MPI/Rmpi
Recursion

PHP Call R
Basic C
R Call Fortran/C
R Call GSL
C Call R API
C Call R Objects
Standalone

Make Packages
C Pointer
Debug




Section: Environment

This section will talk about how we use environments and it's utility functions including environment(), assign(), eval(), get(), etc. Basically, your current working environment is in .GlobalEnv, and each function has it's own environment.


Examples:
  1. Environment

        
    rm(list = ls())
    .GlobalEnv
    parent.env(a.new.env <- new.env())
    parent.env(an.env <- environment())
    parent.env(a.base <- baseenv())
    parent.env(a.new.env <- new.env(parent = a.base))
    ls()
    

    At the end, there are 3 environments in the current environment .GlobalEnv. Note that the parent of "a.new.env" is "<environment: base>" rather than "a.base"!! The following example fixes this.

  2. assign(), eval(), and get()

        
    rm(list = ls())
    .GlobalEnv
    parent.env(a.parent.env <- new.env())
    
    ### Two of the followings are the same.
    assign("a.children.env", new.env(), envir = a.parent.env)
    eval(parse(text = "a.children.env <- new.env()"), envir = a.parent.env)
    
    ### Two of the followings are the same.
    ls()
    eval(ls(), envir = a.parent.env)
    
    ### There is a object inside "a.parent.env".
    ls(envir = a.parent.env)
    
    assign("a.value", 10, envir = a.parent.env)
    eval(parse(text = "a.value <- a.value + 1"), envir = a.parent.env)
    
    ### There are two objects now.
    ls(envir = a.parent.env)
    
    ### This should return 11.
    get("a.value", envir = a.parent.env)
    

    There is a parent environment attached in .GlobalEnv, and a childrend environment attached inside the parent environment. In different environment, the assign() and eval() can alter the objects, and get() can access the object values.

  3. Function is a TEMPORARY environment

        
    rm(list = ls())
    parent.env(.GlobalEnv)      ### This is an interesting result.
    
    a.function <- function(){
      a <- 1
      print(environment())      ### print current environment
      environment()
    }
    an.env <- a.function()      ### This is an interesting environment.
    an.env                      ### This should be the same as the above.
    
    ls(envir = an.env)
    get("a", envir = an.env)
    

    I create an environment where is created by a.function() and executing itself, then I store the environment in .GlobalEnv.


[ Go to top ]

Maintained: Wei-Chen Chen
E-Mail: wccsnow @ gmail.com
Last Revised: Dec 12 2016, 09:44 (CST Taipei, Taiwan)
Created: Oct 06 2003
free counters Best Resolution
IE6.0
1280x1024
small font