functions setting in R

本文探讨了LexicalScoping和DynamicScoping两种函数作用域的区别,并通过R语言中的实例展示了自由变量查找的不同方式。此外,还介绍了如何在R中创建函数闭包,以及如何检查函数的存在性和运行环境。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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<- 10

f <- 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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值