R really means functions

by Karl-Kuno Kunze

You probably have heard that R is a functional language. This post just reminds you of how far the concept goes.

Example 1

Simple and clear: Functions go like this:

coolFun <- function(x) {
  cat(x, "and ")
  cat(x**2)
}
coolFun(2)
## 2 and 4

More than one statement are written inside curly brackets.

However, the curly brackets represent themselves a function. Therefore, this:

coolFun <- function(x) '{'(cat(x, "and "), cat(x**2) )
coolFun(2)
## 2 and 4

works as nicely.

Example 2

Simple and clear: The selection operator for vectors and the like.

myVec <- c(1:3)
myVec[2]
## [1] 2

How about this:

'['(myVec,2)
## [1] 2

In this way you can use selections in apply statements e.g. for rolling averages

mySeries <- c(1:9)
winLength <- 3
sapply(c(1:7),
       function(n) mean('['(mySeries, c(n, n + winLength - 1 ))))
## [1] 2 3 4 5 6 7 8

The anonymous function calculates averages of subseries of mySeries starting at n with a window size of winLength. The only argument is n. This function is applied to the series starting at 1 and ending at 7.