Use of $ and %% operators in R

You are not really pulling a value from a function but rather from the list object that the function returns. $ is actually an infix that takes two arguments, the values preceding and following it. It is a convenience function designed that uses non-standard evaluation of its second argument. It's called non-standard because the unquoted characters following $ are first quoted before being used to extract a named element from the first argument.

 t.test  # is the function
 t.test(x) # is a named list with one of the names being "p.value"
 

The value can be pulled in one of three ways:

 t.test(x)$p.value
 t.test(x)[['p.value']]  # numeric vector
 t.test(x)['p.value']  # a list with one item

 my.name.for.p.val <- 'p.value'
 t.test(x)[[ my.name.for.p.val ]]

When you surround a set of characters with flanking "%"-signs you can create your own vectorized infix function. If you wanted a pmax for which the defautl was na.rm=TRUE do this:

 '%mypmax%' <- function(x,y) pmax(x,y, na.rm=TRUE)

And then use it without quotes:

> c(1:10, NA) %mypmax% c(NA,10:1)
 [1]  1 10  9  8  7  6  7  8  9 10  1

Tags:

Operators

R