Dan*_*iel 17 scope r function lexical-scope
通过学习R,我只是碰到下面的代码解释这里.
open.account <- function(total) {
list(
deposit = function(amount) {
if(amount <= 0)
stop("Deposits must be positive!\n")
total <<- total + amount
cat(amount, "deposited. Your balance is", total, "\n\n")
},
withdraw = function(amount) {
if(amount > total)
stop("You don't have that much money!\n")
total <<- total - amount
cat(amount, "withdrawn. Your balance is", total, "\n\n")
},
balance = function() {
cat("Your balance is", total, "\n\n")
}
)
}
ross <- open.account(100)
robert <- open.account(200)
ross$withdraw(30)
ross$balance()
robert$balance()
ross$deposit(50)
ross$balance()
ross$withdraw(500)
Run Code Online (Sandbox Code Playgroud)
什么是最我对这个代码的兴趣,学习使用"$"美元符号,其是指一个特定internal function的 open.account()功能.我的意思是这部分:
ross$withdraw(30)
ross$balance()
robert$balance()
ross$deposit(50)
ross$balance()
ross$withdraw(500)
Run Code Online (Sandbox Code Playgroud)
问题:
1 -什么是美元符号的意义"$"在R function()?
2-如何在函数中识别其属性,特别是对于从其他函数中采用的函数(即您没有编写它)?
我使用了以下脚本
> grep("$", open.account())
[1] 1 2 3
Run Code Online (Sandbox Code Playgroud)
但它没有用我想找到一种方法来提取可以通过"$"引用的内部函数的名称,而不需要通过调用和搜索编写的代码 > open.account().
例如,如果open.account()我想看到这样的事情:
$deposit
$withdraw
$balance
Run Code Online (Sandbox Code Playgroud)
3-有没有可以参考的参考资料?
TNX!
MrF*_*ick 33
将$允许你提取从命名列表中的名称元素.例如
x <- list(a=1, b=2, c=3)
x$b
# [1] 2
Run Code Online (Sandbox Code Playgroud)
您可以使用找到列表的名称 names()
names(x)
# [1] "a" "b" "c"
Run Code Online (Sandbox Code Playgroud)
这是一个基本的提取操作符.您可以通过键入?ExtractR 来查看相应的帮助页面.
Len*_*ski 18
有R中四种形式提取操作的:[,[[,$,和@.第四种形式也称为插槽操作符,用于从使用S4对象系统构建的对象中提取内容,也称为R中正式定义的对象.大多数R用户不使用正式定义的对象,因此我们不会在这里讨论插槽操作符.
第一种形式[可用于从矢量,列表或数据帧中提取内容.
第二种和第三种形式,[[并$从单个对象中提取内容.
该$操作员使用一个名称来进行提取作为anObject$aName.因此,它使人们能够根据名称从列表中提取项目.由于a data.frame()也是a list(),因此它特别适合访问数据框中的列.也就是说,这种形式不适用于计算索引或函数中的变量替换.
类似地,可以使用[或[[表单从对象中提取命名项,例如anObject["namedItem"]或anObject[["namedItem"]].
有关使用每种运算符形式的更多详细信息和示例,请阅读我的文章提取运算符的表单.