【发布时间】:2017-07-22 10:54:27
【问题描述】:
通过学习R,刚好碰到下面的代码解释here。
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() 函数中的特定internal function。我的意思是这部分:
ross$withdraw(30)
ross$balance()
robert$balance()
ross$deposit(50)
ross$balance()
ross$withdraw(500)
问题:
1- R function() 中的美元符号 "$" 是什么意思?
2- 如何在函数中识别它的属性,特别是你从其他人那里采用的函数(即不是你写的)?
我使用了以下脚本
> grep("$", open.account())
[1] 1 2 3
但这没有用我想找到一种方法来提取可以通过“$”引用的内部函数的名称,而不仅仅是通过调用和搜索书面代码为> open.account()。
例如open.account(),我希望看到这样的内容:
$deposit
$withdraw
$balance
3- 有什么参考资料可以让我了解更多信息吗?
tnx!
【问题讨论】:
-
查看帮助文件:
?"$". -
想要添加 $ 的特殊之处在于它会进行部分匹配
标签: r function scope lexical-scope