Beruflich Dokumente
Kultur Dokumente
http://www.uweziegenhagen.de
Part 4
Programming R
Functions
Loops
Conditions
Packages
Functions in R
1-1
Part 4
Functions
1
2
3
4
1
2
3
4
Functions in R
1-2
Part 4
1-3
Functions
1
2
3
4
5
1
2
Functions in R
Part 4
Functions
1
2
3
4
5
6
Functions in R
1-4
Part 4
Functions
1
2
3
4
5
6
7
8
9
10
Functions in R
1-5
Part 4
Functions
Functions in R
1-6
Part 4
# simple if
x <- 1
if ( x = = 2) { print ( " x = 2 " ) }
# if - else
x <- 1
if ( x = = 2) {
print ( " x = 2 " )
} else {
print ( " x ! = 2 " )
}
# ifelse function , takes a logical vector
> y < - sample . int (5)
[1] 5 3 1 4 2
ifelse ( y > 2 , " high " , " low " )
[1] " high " " high " " low " " high " " low "
Functions in R
1-7
Part 4
1
2
3
4
5
6
7
8
9
10
11
Functions in R
1-8
Part 4
1-9
3
4
5
6
7
8
9
10
11
12
Part 4
1
2
3
4
5
i <- 0
while ( i < 4) {
i < - i +1
print ( i )
}
Functions in R
1-10
Part 4
1
2
3
4
5
6
i <- 0
repeat {
i < - i +1
print ( i )
if ( i = = 4) break
}
Functions in R
1-11
Part 4
Functions in R
1-12
Part 4
1-13
apply()
Functions in R
Part 4
lapply()
1
2
3
4
5
6
7
8
9
10
11
[[2]]
[1] 5.5
> sapply (c , mean )
[1] 6.5 5.5
Functions in R
1-14
Part 4
1-15
mapply()
Like sapply() but applies over the first elements of each argument
1
2
3
4
5
6
7
[[2]]
[1] 3.141593 3.141593
8
9
10
11
12
13
14
[[3]]
[1] 3.141593
# equivalent to :
rep ( pi , 3)
rep ( pi , 2)
rep ( pi , 1)
Functions in R
Part 4
tapply()
Functions in R
1-16
Part 4
1-17
Functions in R
Part 4
1-18
Debugger commands:
n advance to next step
c continue to the end of current loop or function
where print a stack trace
Q exit the browser
You can also use any R command! Check the value of variables,
length/dimensions of matrices, etc.
Functions in R
Part 4
1-19
You can also start the debugger on a certain line of code, rather
than when a function is called:
1
2
3
Functions in R
Part 4
Functions in R
1-20