# R Notes: Functions

**F# and Data Mining**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

R’s semantics is modeled after Scheme. Scheme is a functional language and R is functional too. I am writing about the functions in R and many R’s strange usages are just syntax sugars of special function calls.

# What is `rownames(x) <- c('A','B','C')`

?

y <- c(1, 2, 3, 4, 5, 6)<br />x <- matrix(y, nrow = 3, ncol = 2)<br />rownames(x) <- c("A", "B", "C")<br />x<br />

## [,1] [,2]<br />## A 1 4<br />## B 2 5<br />## C 3 6<br />

How can we assign `c('A','B','C')`

to the return value of `rownames(x)`

, yet the assignment effect is done on `x`

?! This is because the statement is a syntax sugar for the following function call:

x <- `rownames<-`(x, c("A1", "B1", "C1"))<br />

First, `rownames<-`

is indeed a function! Because it has special characters, to apply it we need put `"`

around the function name. Second, `"rownames<-"(x, c('A1','B1','C1'))`

is a **pure** function call. It returns a new copy of `x`

and does not change the row names of `x`

. To take the assignment effect, we must assign the return value back to `x`

explicitly.

The technical term for `functionname<-`

is **replacement function**. The general rule:

`f(x) <- y`

is transformed as `x <- "f<-(x,y)"`

.

Besides `rownames`

, there are many other functions that have a twin replacement function, for example, `diag`

and `length`

.

A special case is index operator `"["`

. Its replacement function is `"[<-"`

:

y <- c(1, 2, 3)<br />"["(y,1)<br />

## [1] 1<br />

`[<-`(y, 2, 100)<br />

## [1] 1 100 3<br />

More examples at R language defination 3.4.4.

# Operators are functions

Operators in R are indeed function calls.

"+"(c(1,2), 2) # same as c(1,2) + 2<br />

## [1] 3 4<br />

Because operators are functions, we can define new operators using function syntax:

# strict vector add<br />"%++%" <- function(x, y) {<br /> n <- length(x)<br /> m <- length(y)<br /> if (n != m) {<br /> stop("length does not match")<br /> } else {<br /> x + y<br /> }<br />}<br />

Self-defined operators become more powerful when used with S3 objects (see below).

# S3 functions

There are two object systems in R, S3 and S4. S3 objects are lists, so its fields are accessed by the same operator to access list fields `$`

. S4 objects are intended to be safer than S4 objects. Its fields are accessed by `@`

. Many packages, especially those with a long history, such as `lars`

, `rpart`

and `randomForest`

, use S3 objects. S3 objects are easier to use and understand.

Knowing how to implement an S3 object is very useful when we need to check the source code of a specific R package. And when we want to release a small piece of code for others to use, S3 objects provide a simple interface.

The easiest way to understand S3 objects is the following analogy:

R | ANSI C |
---|---|

S3 object/R list object | C `struct` |

S3 functions | functions on struct |

struct MyVec {<br /> int *A;<br /> int n;<br />};<br /><br />int safe_get(struct MyVec vec, int i) {<br /> if (i<0 || i>=vec.n) {<br /> fprintf(stderr, "index error");<br /> exit(1);<br /> }<br /> return vec.A[i];<br />}<br /><br />

In R, the S3 object is implemented as:

vec <- list()<br />vec$A <- c(1, 2, 3)<br />vec$n <- length(vec$A)<br />class(vec) <- "MyVec"<br />

In the S3 object system, the method names cannot be set freely as those in C. They must follow a pattern: “functionname.classname”. Here my class name is `MyVec`

, so all the methods names must end with `.MyVec`

.

"[.MyVec" <- function(vec, i) {<br /> if (i <= 0 || i > vec$n) {<br /> stop("index error")<br /> }<br /> vec$A[i]<br />}<br />

Let's implement the replacement function too:

"[<-.MyVec" <- function(vec, i, value) {<br /> if (i <= 0 || i > vec$n) <br /> stop("index error")<br /> vec$A[i] <- value<br /> vec<br />}<br />

Let's play with MyVec objects:

vec[3]<br />

## [1] 3<br />

vec[2] <- 100<br />vec[30]<br />

## Error: index error<br />

We can also add other member functions for `MyVec`

such as `summary.MyVec`

, `print.MyVec`

, `plot.Vec`

, etc. To use these functions, we don't have to specify the full function names, we can just use `summary`

, `print`

, and `plot`

. R will inspect the S3 class type (in our case, it is `MyVec`

) and find the corresponding functions automatically.

# Default parameters and `...`

Many functions in R have a long list of parameters. For example `plot`

function. It would becomes tedious and even impossible for the end user to assign the values for every parameter. So to have a clean interface, R supports default parameters. A simple example below:

add2 <- function(a, b = 10) {<br /> a + b<br />}<br />add2(5)<br />

## [1] 15<br />

What I want to emphasize in this section is `...`

, which is called **variable number of arguments**. And it is universal in R to implement good function interfaces. If you read the documents of R's general functions such as `summary`

and `plot`

, most of their interfaces include `...`

.

Consider the following case: I am implementing a statistical function `garchFit`

, say GARCH model calibration, I used a optimizer `optim`

which has a lot of parameters. Now I need to think about the API of my GARCH calibration function because I want others to use it as well. Shall I expose parameters of `optim`

in `garchFit`

's parameters? Yes, since I want to give the users of my function some freedom in optimizing. But as we know a single procedure in `optim`

such as `l-bfgs`

would have many parameters. On one side, I want to give the user the option to specify these parameters, on the the side, if I expose all of them in my `garchFit`

, the parameter list would go too long. `...`

comes to the rescue! See the following example:

f1 <- function(a = 1, ...) {<br /> a * f2(...)<br />}<br />f2 <- function(b = 5, ...) {<br /> b * f3(...)<br />}<br />f3 <- function(c = 10) {<br /> c<br />}<br />f1()<br />

## [1] 50<br />

f1(a = 1, b = 2)<br />

## [1] 20<br />

f1(c = 3)<br />

## [1] 15<br />

A simple user of `f1`

would only need to study its exposed parameter `a`

, while advanced users have options to specify parameters in `f2`

and `f3`

when calling `f1`

.

# Global variables

Global variables are readly accessible from any R functions. However, to change the value of a global variable, we need a special assignment operator `<<-`

. Python has similar rules. See the following example:

a <- 100<br />foo <- function() {<br /> b <- a # get a's value<br /> a <- 10 # change a's value fails, (actually done: creates a local variable a, and assign 10)<br /> c(a, b)<br />}<br />foo()<br />

## [1] 10 100<br />

a<br />

## [1] 100<br />

boo <- function() {<br /> a <<- 10<br />}<br />boo()<br />a<br />

## [1] 10<br />

Here our scopes have two layers “global” and top-layer functions (`foo`

and `boo`

). When there are more layers, i.e., nested functions, `<<-`

operator finds the variable with the same name in the closet layer for assignment. But it is generally very bad practice to have same variable names across different function layers (except for variables like `i`

, `j`

, `x`

). `assign`

is more general, check `?assign`

for document.

# Variable scope

I think this is the most tricky part of R programming for C programmers. Because block syntax `{...}`

does not introduce a new scope in R while C/C++/Java/C#/etc all introduce a new scope! In R, only a function introduce a new scope.

Please see my previous post: Subtle Variable Scoping in R

`quote`

, `subsititude`

, `eval`

, etc.

Many language-level features of R such as debugging function `trace`

is implemented in R itself, rather than by interpreter hack because R supports meta-programming. I will write another post for these special functions.

**leave a comment**for the author, please follow the link and comment on their blog:

**F# and Data Mining**.

R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.