Writing Functions in R
Grouped expressions
• R is an expression language in the sense that its only command
type is a function or expression which returns a result.
• Commands may be grouped together in braces, {expr1; ...; expr
m}, in which case the value of the group is the result of the last
expression in the group evaluated.
Control structures
• A key element of programming is that you can use control
structures to control the flow of execution of the program.
• Commonly used control structures are
if, else: testing a condition and acting on it
Types of loops
for: execute a loop for a fixed number of times
while: execute a loop while a condition is true
repeat: execute a loop until seeing a break
break: stop the execution of a loop
next: skip an iteration of a loop
return: exit a function
Conditional execution
• The general form of the if construction has the form
if(<condition>){ # do something
} else # do something else
or
if(<condition1>){# do something
}elseif (<condition2>){# do different
}else # do something
• Example(s)
abs<-function(x){
x=-23
if(x<0){ if(x<0) out=-x
y<-(-x) else out=x
} else{
out
y<-x
} }
if statement….
• The operators && and || are often used as part of the condition in an if statement.
• Whereas & and | apply element-wise to vectors, && and || apply to vectors of
length one, and only evaluate their second argument if necessary.
• The shorter form (& and |) perform element-wise comparisons in much the same
way as arithmetic operators.
• The longer form (&& and ||) evaluates left to right, examining only the first
element of each vector. Evaluation proceeds only until the result is determined.
• >x<-c(1>2,2<3,3==4)
• x
• >y<-c(1<2,2<3,3==4)
• y
• >x&&y
• >x&y
Repetitive execution: for , while and repeat
• for loop construction has the form
>for (name in expr_1)
{expr_2}
where name is the loop variable. expr 1 is a vector expression, (often a
sequence like 1:20), and expr 2 is repeatedly evaluated as name
ranges through the values in the vector result of expr 1.
j<-k<-0
Example(s)
for (i in 1:5) {
for(i in 1:10){
j<-j+1
print(i) k<-k+i*j
} print(i+j+k) }
for loops….
• Loops can be nested
>x<-matrix(1:10,2,5)
for(i in seq_len(nrow(x))){
for(j in seq_len(ncol(x))){
print(x[i,j])
}}
#Example
>z<-c("a","b","c","d")
for(j in 1:4){
print(z[j]) ## Print out each element of z'
}
while
• A while looping facility has the form
while(cond){
expr }
• While loops evaluate a condition repetitively. If the condition is true, then the
expression in the loop body is executed. Otherwise ,the loop will be ended.
Example(s)
>count<-0 y <- 1; j <- 1
while(count<=10){ while (y < 12 & j < 8) {
print(count)
y <- y*2 ; j <- j + 1
count<-count+1
}
repeat
• A repeat looping facility has the form
repeat{
expr
}
• This statement executes the expression in the loop repeatedly until it
sees a break.
Example(s) z <- 3
x=0
repeat {
repeat{
print(x) z<- z^2
if(x>=10){
break if ( z>100 ) {
}else{
x=x+1}
break }
} }
next and return
• next is used to skip an iteration of a loop
for(i in 1:5){
if(i<=3){
next}
print(i)
}
• return signals that a function should exit and return a given value
Writing your own functions
• One of the most powerful features of R is that the user can write their
own functions
• In R, functions are defined as follows
• Functionname<-function(arg_1,arg_2,…) {
expr
}
• The return value of a function is the last expression.
• The return statement can be omitted since by default R will return the
last evaluated expression.
Simple examples
• Consider a function to calculate x2+y2 inputs of x and y
> f<-function(x,y){
value<-x^2+y^2
return(value)
}
• With this function defined, you could perform the calculation using a call such as
>f(x,y)
• Consider a function to calculate the sample variance of x
>variance<-function(x){
sum((x-mean(x))*2)/(length(x)-1)
}
• Then call function by:
>variance(x)
Simple examples
• Consider a function to calculate the two sample t-statistic
• The function is defined as follows:
> twosam <- function(y1, y2) {
n1 <- length(y1); n2 <- length(y2)
yb1 <- mean(y1); yb2 <- mean(y2)
s1 <- var(y1); s2 <- var(y2)
s <- ((n1-1)*s1 + (n2-1)*s2)/(n1+n2-2)
tcal <- (yb1 - yb2)/sqrt(s*(1/n1 + 1/n2))
tcal
}
• With this function defined, you could perform two sample t-tests
using a call such as
> tstat <- twosam(data$male, data$female); tstat
Binary operators
• Binary operators: are operators of functions with two arguments.
• R contains a number of operators. They are listed in the table beiow.
- Minus ,can be unary or binary
+ Plus, can be unary or binary
! Unary not
~ tide, used for model formulae,can be either unary or binary
? Help
: Sequence, binary(in model formulae; interaction)
* Multiplication , binary
/ Division , binary
^ Exponentiation , binary
Binary operators cont’d…
%x% special binary operators,x can be replaced by
any valid name
%% modulus, binary
%/% integer division, binary
%*% matrix product, binary
< less than, binary
> Greater than, binary
Binary operators cont’d…
>= Greater than or equal to, binary
<= less than or equal to, binary
& And , binary, vectorized
&& And ,binary, not vectorized
| Or, binary,vectorized
|| Or, binary, not vectorized
< left assignment, binary
-> right assignment, binary
Binary operators cont’d…
>= Greater than or equal to, binary
<= less than or equal to, binary
& And , binary, vectorized
&& And ,binary, not vectorized
| Or, binary,vectorized
|| Or, binary, not vectorized
< left assignment, binary
-> right assignment, binary
More advanced examples