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]))
}
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
y=ifelse(x<3,0,x)
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
}