R Programing
Steven Gilmour
KCL
0-2
Overview
1.
2.
3.
4.
5.
6.
7.
R
Introduction
Variables, Vectors and Matrices
Data frames
Reading & Writing Data
Exploratory Data Analysis
Graphics
Programming
Programming
Programming
Programming R
Functions
Approximations
Loops
Conditions
Packages
R
1-1
Programming
Functions
myfun < - function ( x ) {
return ( x * x )
}
myfun (2)
1
2
3
4
myfun < - function ( x ) {
x*x
}
myfun (2)
1
2
3
4
If no return() is given, the object last created is returned.
R
1-2
Programming
Functions
myfun < - function (x , a ) {
r < - a * sin ( x )
return ( r )
}
myfun ( pi /2 ,2)
1
2
3
4
5
myfun1 < - function (x , a ) { a * sin ( x ) } # short version
myfun1 ( pi /2 , 2)
1
2
R
1-3
Programming
1-4
Functions
myfun2 < - function (x , a = 1) { # opt . parameter with
default = 1
a * sin ( x )
}
myfun2 ( pi /2 , 2)
myfun2 ( pi /2)
1
2
3
4
5
optional = the function can also be run without specication
R
Programming
Functions
myfun3 < - function (x , a = NULL ) { # with strange
default
if (! is . null ( a ) ) {
a * sin ( x )
} else {
cos ( x )
}
}
myfun3 ( pi /2 , 2)
myfun3 ( pi /2)
1
2
3
4
5
6
7
8
9
R
1-5
Programming
Functions
myfun4 < - function (x , a = 1) {
r1 < - a * sin ( x )
r2 < - a * cos ( x )
return ( r1 , r2 )
# return two results
# don ' t use this , use a list
}
myfun4 ( pi /2)
1
2
3
4
5
6
7
8
R
1-6
Programming
Functions
myfun5 < - function (x , a = 1) {
r1 < - a * sin ( x )
r2 < - a * cos ( x )
return ( list ( r1 , r2 ) ) # one list as result
}
myfun5 ( pi /2)
1
2
3
4
5
6
R
1-7
Programming
Functions
myfun6 < - function (x , a = 1 , b = 2) {
r1 < - a * sin ( x )
r2 < - b * cos ( x )
return ( list ( r1 , r2 ) )
}
myfun6 ( pi /2)
# a= 1 , b=2 ( defaults )
myfun6 ( pi /2 ,1 , 2) # a= 1 , b=2 ( given explicitly )
myfun6 ( pi /2 , 2)
# a= 2 , b=2 ( only a given )
myfun6 ( pi /2 , a = 2) # a= 2 , b=2 ( only a given )
myfun6 ( pi /2 , b = 3) # a= 1 , b=2 ( only b given )
1
2
3
4
5
6
7
8
9
10
R
1-8
Programming
Approximations
Numerical optimization by optimize, optim and
constrOptim
Numerical integration by integrate
Use uniroot for calculating unit roots
R
1-9
Programming
1-10
Minimization
f1 < - function (x , a ) {( x - a ) ^2} # analytical
solution !
xmin < - optimize ( f1 , c (0 , 1) , tol = 0.0001 , a = 1/3)
1
2
3
f2 < - function (x , a ) { log ( x ) ^2 + sqrt ( x * a ) } #
analytical solution ?
xmin < - optimize ( f2 , c (0 , 10) , tol = 0.0001 , a =
1/3)
4
5
R
Programming
1-11
Several Parameters
f3 < - function ( x ) { log ( x [1]) ^2 + sqrt (x [1]* x [2]) }
xmin1 < - optim ( par = c (1 , 2) , fn = f3 , gr = NULL )
1
2
3
g3 < - function ( x ) {
g1 < - 2 * log (x [1]) / x [1] + x [2]/(2* sqrt ( x [1]* x
[2]) )
g2 < - x [1]/(2* sqrt (x [1]* x [2]) )
c ( g1 , g2 )
}
xmin2 < - optim ( par = c (1 , 2) , fn = f3 , gr = g3 ,
method = " BFGS " )
4
5
6
7
8
9
R
Programming
1-12
Linear Constraints
# constraints
# ui %*% theta - ci >= 0
1
2
3
ci = matrix ( c (0 , 0) , ncol = 1)
ui = diag (1 , 2 , 2)
4
5
6
xmin < - constrOptim ( theta = c (1 , 1) , f = f3 , grad =
NULL , ui = ui , ci = ci )
7
R
Programming
Algebraic Computations
Similar to Mathematica, R can compute analytical results.
deriv (~ log ( x1 ) ^2 + sqrt ( x1 * x2 ) , " x1 " )
deriv (~ log ( x1 ) ^2 + sqrt ( x1 * x2 ) , " x2 " )
1
2
However, the results are just roughly simplied.
R
1-13
Programming
Using Sets
a
b
a
b
a
b
a
a
b
a
b
1
2
3
4
5
6
7
8
9
10
11
< - 1:3
< - 2:6
% in % b
% in % a
< - c ( "A " ," B " ) ; b < - LETTERS [2:6]
% in % b
% in % a
LETTERS is a special predened variable, containing 'A' to 'Z',
(letters='a' to 'z')
R
1-14
Programming
Loops and Conditions - IF
# simple if
x <- 1
if ( x = = 2) { print ( " x = 2 " ) }
# if - else
x <- 1
if ( x = = 2) {
print ( " x = 2 " )
} else {
print ( " x != 2 " )
}
1
2
3
4
5
6
7
8
9
10
R
1-15
Programming
1-16
Loops and Conditions - FOR
for ( i in 1:4) { print ( i ) }
for ( i in letters [1:4]) { print ( i ) }
1
2
3
a < - numeric (400) # generate empty a of length 400
for ( i in 1:400) { a [ i ] = i } # fill a with 1:400
# takes much longer than a < - 1:400
4
5
6
R
Programming
Loops and Conditions - WHILE
i <- 0
while ( i < 4) {
i <- i + 1
print ( i )
}
1
2
3
4
5
Do NOT forget the increase of the counter variable i !
R
1-17
Programming
Loops and Conditions - REPEAT
i < - 0;
repeat {
i <- i + 1;
print ( i );
if ( i = = 4) break
}
1
2
3
4
5
6
If no break is given, loops runs forever!
R
1-18
Programming
Loops and Conditions - IFELSE
ifelse allows shorter if-else syntax
ifelse(boolean check, if-case, else-case)
x < - c (6: -4)
sqrt ( x ) # gives warning
sqrt ( ifelse ( x >= 0, x , NA ) )# no warning
1
2
3
R
1-19
Programming
1-20
Loops and Conditions - SWITCH
switch avoids the use of nested if-else constructs, however it looks
tricky. If type is numeric, switch uses the i -th item.
rootsquare < - function (x , type ) {
switch ( type ,
square = x *x ,
root = sqrt ( x ) )
}
rootsquare (10 , 1)
rootsquare (10 , 2)
1
2
3
4
5
6
7
R
Programming
Loops and Conditions - SWITCH
If type is a string, R matches the string.
rootsquare < - function (x , type ) {
switch ( type ,
square = x *x ,
root = sqrt ( x ) )
}
rootsquare (10 , " square " ) # ok
rootsquare (10 , " root " )
# ok
rootsquare (10 , " ROOT " )
# returns NULL
1
2
3
4
5
6
7
8
R
1-21
Programming
Loops and Conditions - SWITCH
another example for switch
centre < - function (x , type ) {
switch ( type ,
mean = mean ( x ) ,
median = median ( x) ,
trimmed = mean (x , trim = .1) )
}
x < - rcauchy (1000)
centre (x , " mean " )
centre (x , " median " )
centre (x , " trimmed " )
1
2
3
4
5
6
7
8
9
10
R
1-22
Programming
1-23
Loops and Conditions
system.time() measures the time necessary to run a command.
> x < - c (1:50000)
> system . time ( for (i in 1:50000) { x [ i ] < - rnorm (1) })
User
System verstrichen
0.67
0.01
0.69
> system . time ( x < - rnorm (50000) )
User
System verstrichen
0.01
0.00
0.01
1
2
3
4
5
6
7
⇒ use matrix functions
R
Programming
1-24
The apply() commands
these commands allow functions to be run on matrices.
apply()
tapply()
lapply()
sapply()
mapply()
R
Function used on matrix
table grouped by factors
on lists and vectors; returns a list
like lapply(), returns vector/matrix
multivariate sapply()
Programming
apply()
apply(data, margin, function)
> matrix (1:10 , nrow = 2) - > a
> apply (a , 1 , mean )
[1] 5 6
> apply (a , 2 , mean )
[1] 1.5 3.5 5.5 7.5 9.5
1
2
3
4
5
R
1-25
Programming
lapply()
> matrix (2:11 , nrow = 2) - > a
> matrix (1:10 , nrow = 2) - > b
> c = list (a , b )
> lapply (c , mean )
[[1]]
[1] 6.5
1
2
3
4
5
6
7
[[2]]
[1] 5.5
8
9
R
1-26
Programming
sapply()
> matrix (2:11 , nrow = 2) - > a
> matrix (1:10 , nrow = 2) - > b
> c = list (a , b )
> sapply (c , mean )
[1] 6.5 5.5
1
2
3
4
5
R
1-27
Programming
mapply()
> mapply ( rep , pi , 3:1)
[[1]]
[1] 3.141593 3.141593 3.141593
1
2
3
4
[[2]]
[1] 3.141593 3.141593
5
6
7
[[3]]
[1] 3.141593
8
9
R
1-28
Programming
tapply()
requires variable, Factor and function
> data ( iris )
> attach iris
> tapply ( Sepal . Width , Species , mean )
setosa versicolor virginica
3.428
2.770
2.974
1
2
3
4
5
R
1-29
Programming
1-30
GUIs with Tcl/Tk
examples taken from http://bioinf.wehi.edu.au/
~wettenhall/RTclTkExamples/mb.html
require ( tcltk )
ReturnVal < - tkmessageBox ( title = " Greetings from R
TclTk " ,
message = " Hello , world ! " , icon = " info " , type = " ok
")
1
2
3
R
Programming
1-31
GUIs with Tcl/Tk - MessageBoxes
require ( tcltk )
tkmessageBox ( message = " Do you want to save before
quitting ? " ,
icon = " question " , type = " yesnocancel " , default = "
yes " )
1
2
3
R
Programming
1-32
Tips & Hints
Some useful stu:
system()
xtable()
latex()
eval()
parse()
R
runs OS commands
generates LaTeX code (package xtable)
generates LaTeX code (package Hmisc)
evaluate string as command
returns the parsed but unevaluated expressions in a
list
© Copyright 2026 Paperzz