4

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!

thelatemail
  • 91,185
  • 12
  • 128
  • 188
statechular
  • 273
  • 3
  • 12

1 Answers1

10

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?

Community
  • 1
  • 1
Alex
  • 15,186
  • 15
  • 73
  • 127
  • 1
    Thank Alex! That makes sense. Also found two other advantages of using backticks: (1) allows user-defined infix functions; and (2) replacement functions – statechular Sep 18 '14 at 02:02
  • thanks, I've updated by answer to include these cases. – Alex Sep 18 '14 at 02:19
  • 1
    What's even more interesting about the names is you can't assign numbers with backticks, but R can... `split(1, 1)` But you can access them with backticks with split(1,1)$`1` – Rich Scriven Sep 18 '14 at 04:34
  • interesting indeed! unfortunately we don't find much help in querying the underlying code of `split`. However, querying `reshape::cast` gives this bit: ` if (any(names(data) == value)) names(data)[names(data) == value] <- "value"` – Alex Sep 18 '14 at 04:54