R Programing Language and User-Written Functions

As we already said, R is also a progamming language with all the usual parts. First throughout this page let x=c(1,2,5,3,4,7,3,4,6,8,5)

Loops

The most common loop is a "for" loop:

y=rep(0,5)
for(i in 1:5) y[i]=mean(sample(x,3))

If a number of calculations should be done within a loop use { }:

y=matrix(0,5,2)
for(i in 1:5) {
 y[i,1]=mean(sample(x,1))
 y[i,2]=mean(sample(x,3))
}

Loops can be nested:

for(i in 1:5) {
 for(j in 1:2) y[i,j]=mean(sample(x,c(1,3)[j]))

}

Control Structures

if-else Statement

performs branched excecution:

for(i in 1:11) {
 if(x[i]<3) {
  x[i]=x[i]^2
 }
 else {
  x[i]=sqrt(x[i])
 }
}

An extension of an if-else is the case statement

ifelse Statement

Sometimes the above can be simplified:

y=ifelse(x<3,0,x)

User-Written Functions

Writing your own functions is a very important part of using R, for example to do simulations and also to do data analysis. First you should install a good ASCII editor on you computer, for example notepad2.exe, a very nice editor for programming. In R you need to type the following sequence so that R knows you want to use this editor:

options(editor="C:\\R\\notepad2.exe")

(change the path to the directory where notepad2 is located)

Now when you type fix(myfun) R will open this editor and you can write your function. When you are done type ALT-f-s (to save) and Alt-f-x (to exit the editor). If your program has a syntax mistake R will give you an error message (with the line where the mistake is). Type myfun=edit() to fix the mistake.

As an illustration let's write a little function that calculates the five-number summary of a vector:

function (x)
{
   y=rep(0,5)
   names(y)=c("Min","Q1","Median","Q3","Max")
   y[c(1,5)]=c(min(x),max(x))
   y[c(2,4)]=quantile(x,c(0.25,0.75))
   y[3]=median(x)
   y
}