1.2 环境空间的层次结构
R语言的环境是一种有层次关系的结构,每个环境都有上一层环境,直到最顶层的空环境。R语言中有5种环境的定义 全局环境,内部环境,父环境,空环境 和 包环境。
- 当前环境,即用户环境,是用户程序运行的环境空间。
- 内部环境,构造出来的环境,可以是通过 new.env()函数显示创建的环境空间,也可以是匿名的环境空间。
- 父环境,即上一层环境,环境空间的上一层。
- 空环境,即顶层环境,没有父环境空间。
- 包环境,包封装的环境空间。
# 当前环境> environment()<environment: R_GlobalEnv># 内部环境> e1 <- new.env()> e1<environment: 0x3e28948># 父环境> parent.env(e1)<environment: R_GlobalEnv># 空环境> emptyenv()<environment: R_EmptyEnv># 包环境> baseenv()<environment: base>可以用search() 函数查看当前环境中加载的R包。
# 查看环境空间> search() [1] ".GlobalEnv" "package:pryr" "package:stats" [4] "package:graphics" "package:grDevices" "package:utils" [7] "package:datasets" "package:methods" "Autoloads"[10] "package:base"# 当前的环境空间> .GlobalEnv<environment: R_GlobalEnv>> parent.frame()<environment: R_GlobalEnv>查看父环境空间
# e1环境的父环境空间> parent.env(e1)<environment: R_GlobalEnv># 当前环境的父环境空间> parent.env(environment())<environment: package:pryr>attr(,"name")[1] "package:pryr"attr(,"path")[1] "/home/conan/R/x86_64-pc-linux-gnu-library/3.0/pryr"# base包环境的父环境空间> parent.env(baseenv())<environment: R_EmptyEnv># 空环境的父环境空间,因没有父环境,所以出现错误> parent.env(emptyenv())Error in parent.env(emptyenv()) : the empty environment has no parent既然环境空间是有层次关系的,那么我们打印这个层次结构,从自定义的e1环境到空环境。
# 递归打印父环境空间> parent.call<-function(e){+ print(e)+ if(is.environment(e) & !identical(emptyenv(),e)){+ parent.call(parent.env(e))+ }+ }# 运行函数> parent.call(e1)<environment: 0x366bf18><environment: R_GlobalEnv><environment: package:pryr>attr(,"name")[1] "package:pryr"attr(,"path")[1] "/home/conan/R/x86_64-pc-linux-gnu-library/3.0/pryr"<environment: package:stats>attr(,"name")[1] "package:stats"attr(,"path")[1] "/usr/lib/R/library/stats"<environment: package:graphics>attr(,"name")[1] "package:graphics"attr(,"path")[1] "/usr/lib/R/library/graphics"<environment: package:grDevices>attr(,"name")[1] "package:grDevices"attr(,"path")[1] "/usr/lib/R/library/grDevices"<environment: package:utils>attr(,"name")[1] "package:utils"attr(,"path")[1] "/usr/lib/R/library/utils"<environment: package:datasets>attr(,"name")[1] "package:datasets"attr(,"path")[1] "/usr/lib/R/library/datasets"<environment: package:methods>attr(,"name")[1] "package:methods"attr(,"path")[1] "/usr/lib/R/library/methods"<environment: 0x20cb5d0>attr(,"name")[1] "Autoloads"<environment: base><environment: R_EmptyEnv>通过找父环境空间,我们看到整个环境空间的层次结构,如图所示。
通过层次结构图,又可以发现R包的加载顺序。 最先加载的是base包,然后通过base::Autoloads()函数,分别加载6个基础包,上层的pryr包则是我手动加载的,最后以R_GlobalEnv环境为当前运行环境空间,内部环境空间是R_GlobalEnv环境的下层环境空间。 |