It may be a silly question but I have been bothered for quite a while. I've seen people use single quotation marks to surround the function name when they are defining a function. I keep wondering the benefit of doing so. Below is a naive example
'row.mean' <- function(mat){
return(apply(mat, 1, mean))
}
Thanks in advance!
Going off Richard's assumption, the back ticks allows you to use symbols in names which are normally not allowed. See:
`add+5` <- function(x) {return(x+5)}
defines a function, but
add+5 <- function(x) {return(x+5)}
returns
Error in add + 5 <- function(x) { : object 'add' not found
To refer to the function, you need to explicitly use the back ticks as well.
> `add+5`(3)
[1] 8
To see the code for this function, simply call it without its arguments:
> `add+5`
function(x) {return(x+5)}
See also this comment which deals with the difference between the backtick and quotes in name assignment: https://stat.ethz.ch/pipermail/r-help/2006-December/121608.html
Note, the usage of back ticks is much more general. For example, in a data frame you can have columns named with integers (maybe from using reshape::cast
on integer factors).
For example:
test = data.frame(a = "a", b = "b")
names(test) <- c(1,2)
and to retrieve these columns you can use the backtick in conjunction with the $
operator, e.g.:
> test$1
Error: unexpected numeric constant in "test$1"
but
> test$`1`
[1] a
Levels: a
Funnily you can't use back ticks in assigning the data frame column names; the following doesn't work:
test = data.frame(`1` = "a", `2` = "b")
And responding to statechular's comments, here are the two more use cases.
In fix functions
Using the %
symbol we can naively define the dot product between vectors x
and y
:
`%.%` <- function(x,y){
sum(x * y)
}
which gives
> c(1,2) %.% c(1,2)
[1] 5
for more, see: http://dennisphdblog.wordpress.com/2010/09/16/infix-functions-in-r/
Replacement functions
Here is a great answer demonstrating what these are: What are Replacement Functions in R?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With