做什么 。 (点)和%(百分比) [英] What do . (dot) and % (percentage) mean in R?
问题描述
我的问题可能听起来很蠢,但我注意到。
和%
My question might sound stupid but I have noticed that .
and %
is often used in R
and to be frank I don't really know why it is used.
我已经在 dplyr
(go 这里为例)和 data.table
(即 .SD
)
I have seen it in dplyr
(go here for an example) and data.table
(i.e. .SD
) but I am sure it must be used in other place as well.
因此,我的问题是:
-
。
是什么意思?是否是某种R
编码最佳实践命名法? (_functionName
通常用在javascript
中,表示它是一个私有函数)。 -
%
的相同问题,也经常在R中使用(即
- What does
.
mean? Is it some kind ofR
coding best practice nomenclature? (i.e._functionName
is often used injavascript
to indicate it is a private function). If yes, what's the rule? - Same question for
%
, which is also often used in R (i.e.%in%
,%>%
,...).
我的猜测总是一直是。
和%
函数,但 data.table
使用。
不遵循这个逻辑,这让我困惑。
My guess always has been that .
and %
are a convenient way to quickly call function but the way data.table
uses .
does not follow this logic, which confuses me.
推荐答案
。
在R中没有固有的/神奇的意义。在符号名中使用。但是因为它是很方便的类型,它已经被赋予特殊的意义通过某些函数和约定在这里只是一些
.
has no inherent/magical meaning in R. It's just another character that you can use in symbol names. But because it is so convenient to type, it has been given special meaning by certain functions and conventions in R. Here are just a few
-
。
用于查找S3通用方法实现。例如,如果你调用类似lm
的对象作为第一个参数的plot
将寻找一个名为plot.lm
的函数,如果找到,则调用该函数。 - 经常
/ code>将会回退
y 在
lm(y〜。,data = dd) / $>
- 在
中的所有其他变量上的/ code> dplyr
使用它作为一个特殊的变量名称指示如do()
的方法的当前data.frame。他们可以很容易地选择使用变量名X
而不是
- 的功能像
bquote
使用。()
作为特殊函数来转义表达式中的变量
- 隐藏并且不会显示
ls()
,除非您调用ls(all.names = TRUE)
到UNIX文件系统行为)
- 在
.
is used look up S3 generic method implementations. For example, if you call a generic function likeplot
with an object of classlm
as the first parameter, then it will look for a function namedplot.lm
and, if found, call that.- often
.
in formulas means "all other variables", for examplelm(y~., data=dd)
will regressy
on all the other variables in the data.framedd
. - libraries like
dplyr
use it as a special variable name do indicate the current data.frame for methods likedo()
. They could just as easily have chosen to use the variable nameX
instead - functions like
bquote
use.()
as a special function to escape variables in expressions - variables that start with a period are considered "hidden" and will not show up with
ls()
unless you callls(all.names=TRUE)
(similar to the UNIX file system behavior)
但是,您也可以只定义一个名为 my.awesome的变量。
However, you can also just define a variable named my.awesome.variable<-42
and it will work just like any other variable.
A %
本身并不意味着任何特殊的,但R允许你以%< something>%
的形式使用两个百分号来定义自己的中缀运算符。如果您定义
A %
by itself doesn't mean anything special, but R allows you to define your own infix operators in the form %<something>%
using two percent signs. If you define
`%myfun%` <- function(a,b) {
a*3-b*2
}
您可以像
5 %myfun% 2
# [1] 11
这篇关于做什么 。 (点)和%(百分比)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!