Function name in single quotes in R
This may be a stupid question, but I've been worried for a long time. I've seen people use single quotes to surround a function name when they define a function. I think about the benefits of this all the time. Below is a naive example
'row.mean' <- function(mat){
return(apply(mat, 1, mean))
}
Thanks in advance!
source to share
Based on Richard's suggestion, back ticks allow characters in names that are not normally allowed. Cm:
`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 call the function, you also need to explicitly use back ticks.
> `add+5`(3)
[1] 8
To see the code for this function, just call it with no arguments:
> `add+5`
function(x) {return(x+5)}
See also this comment which deals with the difference between indentation and quotation marks in naming: https://stat.ethz.ch/pipermail/r-help/2006-December/121608.html
Note: The use of reverse ticks is much more general. For example, in a dataframe, you can have columns with integers (perhaps using reshape::cast
for integer factors).
For example:
test = data.frame(a = "a", b = "b")
names(test) <- c(1,2)
and to retrieve those columns, you can use a backward line in combination with an operator $
, for example:
> test$1
Error: unexpected numeric constant in "test$1"
but
> test$`1`
[1] a
Levels: a
Ridiculously, you can't use back ticks when assigning column names to a data frame; the following doesn't work:
test = data.frame(`1` = "a", `2` = "b")
And responding to statechular comments, here are two more use cases.
In the fix functions
Using a 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
see below: http://dennisphdblog.wordpress.com/2010/09/16/infix-functions-in-r/
Spare functions
Here's a great answer that demonstrates what it is: What are replacement functions in R?
source to share