Presentation 2
Presentation 2
Grouped expressions
>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)
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…
%% modulus, binary