[index]

# Loops, Functions, etc

### Loops [source]

```for(i in 1:10) { 	// runs 10 times
if(i%%2){
cat(i, "is odd\n")
} else {
cat(i, "is even\n")
}
}
#
j<-1
while(j<=10) {
cat(j, "is incremented\n")
j<-j+1
}
```

### Functions [source]

you have to define the function first before you can call them!
```myfunc<-function(p1,p2,p3){
cat("p1:\t",p1,"\n")
cat("p2:\t",p2,"\n")
cat("p3:\t",p3,"\n")
}
myfunc(p1=1,p2=2,p3=3)	// give parameters by name
myfunc(p3=3,p1=1,p2=2)	// the order is insignificant
myfunc(1,2,3) 		// give parameters by position - order of course essential
myfunc(2,3,p1=1) 	// p1 by name, others by position
myfunc(1,2,3,4) 	// too many, won't work
```
use your own function within the apply function
`d1<-matrix(c((1:5),seq(from=0.5,to=2.5,by=0.5)),ncol=2,byrow=F) // matrix d1 just like in previous section`
```myfunc1<-function(myval){
myval<-myval*3
}
d2<-apply(d1,c(1,2),myfunc1) // apply function 'myfunc' to rows and columns of d1
```

### Some Useful Functions

```getwd()					// print working directory
setwd("/path/to/dir")			// change wd
ls()					// list all currently defined variables
str()					// display structure of object
rm(var)					// remove a var
rm(list=ls())				// remove all variables
source()				// load file into workspace
help(getwd) || ?getwd			// invoke help page
example(ls) 				// shows examples from help page
help.search("working directory")	// search for string in documentation
help(getwd) != help(GetWD)		// still case sensitive
install.packages("")			// install external package
library() || require()			// load package into workspace
```