functions setting in R

来源:互联网 发布:淘宝店轮播图片制作 编辑:程序博客网 时间:2024/06/16 23:27

function 调用函数有两种 Lexical Scoping and Dynamic Scoping.
Lexical Scoping : 自由变量(Free Variable)的值在函数定义的环境中寻找
Dynamic Scoping: 自由变量(Free Variable)的值在函数调用时的环境中寻找

环境即作用域

Lexical Scoping Language:
R
Perl
Python
Scheme
Common Lisp.
Dynamic Scoping Language:
C

Example:

y<- 10f <- function(x){        y <- 2        y^2 + g(x)}g <- function(x){        x*y}f(10)

y是g(x)中的自由变量, 所以在f(10)中调用g(X)值时, 由于R 是Lexical Scooping 所以去定义g(x)函数的环境中去找,所以 y = 10.
在Dynamic Scooping 中, y的值会在调用g(x)的环境中去找(即f函数中),即y = 2.
所以在R 中 f(10)的值为 2*2 + 10*10 = 104

查看函数参数函数

args(lm)

在一个函数里调用另外一个函数

make.power <- function(n){        pow <- function(x){                x^n        }        pow}#用心去感受> cube <- make.power(3)> square <- make.power(2)> cube(3)> square(3)#Exploring a Function Closure> ls(environment(cube))[1] "n"   "pow"> get("n",environment(cube))[1] 3

判断在另一个脚本中是否存在要调用的函数
You may want to find a specific function (say our myFirstFun) within a script file, called (say) MyUtils.R, containing other utility functions. In this case, the ‘source’ command will load the function once you’ve found it (and explicitly asked to find a function) with the call to the function exists():

if(exists("myFirstFun", mode = "function"))    source("MyUtils.R") # Read more at: http://scl.io/yxOkcko1#gs.Ze6wtzo

查看运行环境

search()
1 0