本文介绍了美元符号“$"是什么意思?在 R 函数()中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过学习R,我刚遇到下面的代码解释这里.

Through learning R, I just came across the following code explained here.

open.account <- function(total) {
  list(
    deposit = function(amount) {
      if(amount <= 0)
        stop("Deposits must be positive!
")
      total <<- total + amount
      cat(amount, "deposited.  Your balance is", total, "

")
    },
    withdraw = function(amount) {
      if(amount > total)
        stop("You don't have that much money!
")
      total <<- total - amount
      cat(amount, "withdrawn.  Your balance is", total, "

")
    },
    balance = function() {
      cat("Your balance is", total, "

")
    }
  )
}

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() 函数.我的意思是这部分:

What is the most of my interest about this code, learning the use of "$" dollar sign which refer to an specific internal function in open.account() function. I mean this part :

    ross$withdraw(30)
    ross$balance()
    robert$balance()

    ross$deposit(50)
    ross$balance()
    ross$withdraw(500)

问题:

1- R function() 中的美元符号 "$" 是什么意思?
2- 如何在函数中识别它的属性,特别是对于您从其他函数(未编写)中采用的函数?
我使用了以下脚本

1- What is the meaning of the dollar sign "$" in R function() ?
2- How to identify its attributes in functions, specially for the functions that you adopting from other (i.e. you did not write it)?
I used the following script

> grep("$", open.account())
[1] 1 2 3

但它没有用我想找到一种方法来提取可以由$"引用的内部函数的名称,而不仅仅是通过调用和搜索编写的代码作为 >open.account() .
例如,在 open.account() 的情况下,我希望看到这样的内容:

but it is not useful I want to find a way to extract the name(s) of internal functions that can be refer by "$" without just by calling and searching the written code as > open.account() .
For instance in case of open.account() I'd like to see something like this:

$deposit
$withdraw
$balance

3- 是否有任何参考资料可以让我阅读更多相关信息?
tnx!

3- Is there any reference that I can read more about it?
tnx!

推荐答案

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

The $ allows you extract elements by name from a named list. For example

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

您可以使用 names()

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

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

This is a basic extraction operator. You can view the corresponding help page by typing ?Extract in R.

这篇关于美元符号“$"是什么意思?在 R 函数()中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 06:47