【问题标题】:What is the meaning of the dollar sign "$" in R function()?R函数()中的美元符号“$”是什么意思?
【发布时间】: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

但这没有用我想找到一种方法来提取可以通过“$”引用的内部函数的名称,而不仅仅是通过调用和搜索书面代码为&gt; open.account()
例如open.account(),我希望看到这样的内容:

$deposit
$withdraw
$balance

3- 有什么参考资料可以让我了解更多信息吗?
tnx!

【问题讨论】:

  • 查看帮助文件:?"$".
  • 想要添加 $ 的特殊之处在于它会进行部分匹配

标签: r function scope lexical-scope


【解决方案1】:

R 中有四种形式的提取运算符:[[[$@。第四种形式也称为槽运算符,用于从使用 S4 对象系统构建的对象中提取内容,在 R 中也称为 正式定义的对象。大多数 R 初学者不会使用正式定义的对象,所以我们不会在这里讨论槽运算符。

第一种形式[ 可用于从向量、列表或数据帧中提取内容。

第二种和第三种形式,[[$,从单个对象中提取内容。

$ 运算符使用名称来执行提取,如anObject$aName。因此,它使人们能够根据名称从列表中提取项目。由于data.frame() 也是list(),因此它特别适合访问数据框中的列。也就是说,这种形式不适用于计算索引或函数中的变量替换。

同样,可以使用[[[ 形式从对象中提取命名项,例如anObject["namedItem"]anObject[["namedItem"]]

更多详细信息和使用每种运算符形式的示例,请阅读我的文章Forms of the Extract Operator

访问 S3 对象中的名称

Daniel 的帖子包含 R 对象的代码,open.account()。如指定的那样,此对象基于 S3 对象系统,其中对象的行为被定义为 list() 中的项目。

代码在list()depositwithdrawbalance 中创建了三个函数。由于每个函数都有一个名称,open.account() 中的函数可以与names() 函数一起列出,如下图所示。

> names(open.account())
[1] "deposit"  "withdraw" "balance" 
> 

【讨论】:

  • 我要补充一点,df$first_column 等同于 df[, 1, drop = TRUE]
【解决方案2】:

$ 允许您从命名列表中按名称提取元素。例如

x <- list(a=1, b=2, c=3)
x$b
# [1] 2

您可以使用names()找到列表的名称

names(x)
# [1] "a" "b" "c"

这是一个基本的提取运算符。您可以在R中输入?Extract查看相应的帮助页面。

【讨论】:

  • 所以它相当于在大多数其他编程语言中使用点?
猜你喜欢
  • 2020-01-20
  • 1970-01-01
  • 2016-03-04
  • 1970-01-01
  • 2021-11-09
  • 2018-08-08
  • 1970-01-01
  • 2011-08-09
  • 2020-09-22
相关资源
最近更新 更多