What do . (dot) and % (percentage) mean in R?
MrFlick's answer doesn't cover the usage of .
in data.table
;
In data.table
, .
is (essentially) an alias for list
, so any* call to [.data.table
that accepts a list
can also be passed an object wrapped in .()
.
So the following are equivalent:
DT[ , .(x, y)]
DT[ , list(x, y)]
*well, not quite. any use in the j argument, yes; elsewhere is a work in progress, see here.
.
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
.
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 to 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)
However, you can also just define a variable named my.awesome.variable<-42
and it will work just like any other variable.
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
}
you can call it like
5 %myfun% 2
# [1] 11