This section is optional. We consider here the conditional operators (if/else) and loops, which can be avoided working in R.
a=1
b=2
if (a==b) {
print("a equals to b")
} else {
print("a is not equal to b")
}
## use if in-a-line
ifelse(a==b, "equal", "different")
Using loops in R is not recommended. You should avoid them, when possible, because of very slow execution. R is interpretable language, not precompiled (opposite to C).
Runs the same code for each values of the ‘iterator’.
# load some data
Shop = read.table("http://edu.sablab.net/data/txt/shop.txt",header=T,sep="\t")
# print all information for the first client
for (i in 1:ncol(Shop) ){
print(Shop[1,i])
}
Similar to FOR, but without iterator (we have to introduce it)
# print all information for the first client
i=1;
while (i <= ncol(Shop)){
print(Shop[1,i])
i=i+1
}
i=1
repeat {
print(i)
i=i+1
if (i>10) break
}
Keywords break
(stop loop) and next
(switch to the next iteration) help to control the workflow.
Let us write own function to print vectors.
printVector = function(x, name=""){
print(paste("Vector",name,"with",length(x),"elements:")) # print header
if (length(x)>0) # if vector is not empty
for (i in 1:length(x)) # for each element
print(paste(name,"[",i,"] =",as.character(x[i]))) # print value
}
printVector(Shop$Payment, "Payment")
You can run scripts saved on a web page using source()
:
source("http://sablab.net/scripts/plotPCA.r")
plotPCA
These three tasks can be dome without using loops (by matrix operations). So, consider it only as an example.
- Create a matrix 8x8. Fill it with 0. Using “for” loop change elements of the main diagonal to 1.
matrix
,for
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
## [1,] 1 0 0 0 0 0 0 0
## [2,] 0 1 0 0 0 0 0 0
## [3,] 0 0 1 0 0 0 0 0
## [4,] 0 0 0 1 0 0 0 0
## [5,] 0 0 0 0 1 0 0 0
## [6,] 0 0 0 0 0 1 0 0
## [7,] 0 0 0 0 0 0 1 0
## [8,] 0 0 0 0 0 0 0 1
- Fill a matrix 8x8 with “1” to get a chess-board, where 0 codes a white cell and 1 - a black cell. Note, that black cells appear only if the sum of indexes is an even number (1+1=2, 1+3=4, 2+2=4, etc).
matrix
,for
,if
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
## [1,] 1 0 1 0 1 0 1 0
## [2,] 0 1 0 1 0 1 0 1
## [3,] 1 0 1 0 1 0 1 0
## [4,] 0 1 0 1 0 1 0 1
## [5,] 1 0 1 0 1 0 1 0
## [6,] 0 1 0 1 0 1 0 1
## [7,] 1 0 1 0 1 0 1 0
## [8,] 0 1 0 1 0 1 0 1
- Calculate the sum of the first n=1000 members of the series:
s = (4/1) - (4/3) + (4/5) - (4/7) + (4/9) - (4/11) + (4/13) - (4/15) + ...
Can you guess the value when n->Inf ?