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

我与影子孤独终老i 提交于 2019-11-28 09:53:10

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.

There are four forms of the extract operator in R: [, [[, $, and @. The fourth form is also known as the slot operator, and is used to extract content from objects built with the S4 object system, also known as a formally defined object in R. Most beginning R users don't work with formally defined objects, so we won't discuss the slot operator here.

The first form, [, can be used to extract content from vectors, lists, or data frames.

The second and third forms, [[ and $, extract content from a single object.

The $ operator uses a name to perform the extraction as in anObject$aName. Therefore it enables one to extract items from a list based on their names. Since a data.frame() is also a list(), it's particularly well suited for accessing columns in a data frame. That said, this form does not work with a computed index, or variable substitution in a function.

Similarly, one can use the [ or [[ forms to extract a named item from an object, such as anObject["namedItem"] or anObject[["namedItem"]].

For more details and examples using each of the forms of the operator, please read my article Forms of the Extract Operator.

You will often want to select an entire column, namely one specific variable from a data frame. If you want to select all elements of the variable diameter, for example, both of these will do the trick: dataframe_name[,colomn_position] dataframe_name[,"colomn_name"]

however, there is a short-cut. If your columns have names, you can use the $ sign:

dataframe_name$colomn_name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!