Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

What is the meaning of the dollar sign "$" in R function()?

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)

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)

Questions:

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

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- Is there any reference that I can read more about it?
tnx!

question from:https://stackoverflow.com/questions/42560090/what-is-the-meaning-of-the-dollar-sign-in-r-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

You can find the names of a list using names()

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...