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,2))
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(2,3)[j]))
loops also work with other datatypes:
z=c("A","C","D","F")
for(i in z) print(i)
Another useful loop is "repeat":
repeat {
x=rnorm(1)
if(x>0.5) break
}
y=x
for(i in 1:11) {
if(x[i]<3) y[i]=0
else y[i]=1
}
An extension of an if-else is the case statement
y=ifelse(x<3,0,1)
Example write a function that calculates x3-x2+5
f=function(x) {x^3-x^2+5}
Notice that this function is "vectorized", for example
f(c(2,3,-1,0.5))
sometimes this takes a bit of work
Example write a function that calculates that cumulative sum, so x1, x2, ..,xn results in x1, x1+x2, .., x1+x2+..+xn
cs=function (x) {
n=length(x)
for(i in 2:n) x[i]=x[i]+x[i-1]
x
}
(Actually, there already is one, called cumsum)
Writing your own functions is a very important part of using R, for example to do simulations and also to do data analysis. If a function has more than one or two lines it is best to use an editor. 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)
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.
Example write a little function that calculates the five-number summary of a vector:
fix(fivenum)
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
}