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:

1 2 3 4 5 6 |
coolFun <- function(x) { cat(x, "and ") cat(x**2) } coolFun(2) |

1 |
## 2 and 4 |

More than one statement are written inside curly brackets.

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

1 2 3 |
coolFun <- function(x) '{'(cat(x, "and "), cat(x**2) ) coolFun(2) |

1 |
## 2 and 4 |

works as nicely.

## Example 2

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

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

1 |
## [1] 2 |

How about this:

1 2 |
'['(myVec,2) |

1 |
## [1] 2 |

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

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

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.