通过学习 "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)
我对这段代码最感兴趣的地方,是学习了""$" "美元符号的使用,它指的是 "open.account() "函数中一个特定的 "内部函数"。我指的是这一部分:
ross$withdraw(30)
ross$balance()
robert$balance()
ross$deposit(50)
ross$balance()
ross$withdraw(500)
问题: <br>;
1- R``function()
中的美元符号 "$"
是什么意思?
2- 如何在函数中识别其属性,特别是对于您从其他地方采用的函数(即您没有编写它)?
我使用了以下脚本
> grep("$", open.account())
[1] 1 2 3
但是没有什么用处,我想找到一种方法来提取可以用 "$" 引用的内部函数名称,而不只是通过调用和搜索所编写的代码,如 > open.account()
. <br>;
例如,对于open.account()
,我希望看到这样的内容:
$deposit
$withdraw
$balance
3- 有什么参考资料可以让我了解更多相关信息吗? tnx!
R 中的 extract 操作符有四种形式:[
、[[
、$
和@
。第四种形式也被称为槽运算符,用于从使用 S4 对象系统构建的对象中提取内容,在 R 中也被称为 "正式定义的对象"。
第一种形式,[
,可以用来从向量、列表或数据帧中提取内容。
第二和第三种形式,[[
和 $
,可以从单个对象中提取内容。
$操作符使用名称来执行提取,如
anObject$aName中的提取。因此,它可以根据名称从列表中提取项目。由于
data.frame()也是一个
list()`,因此特别适合访问数据帧中的列。尽管如此,这种形式并不适用于计算索引或函数中的变量替换。
同样,我们可以使用 [
或 [[
形式从对象中提取命名项,例如 anObject["namedItem"]
或 anObject[["namedItem"]]
。
有关运算符每种形式的更多细节和示例,请阅读我的文章 Extract 运算符的形式。