If-else statement
for cycles
while
Repeat
Conditional execution of a code. General form:
# if (<condition>){
# what to do if true
#} else if (<other condition>){
# what to do if true
#} else {
# what to do if none of them are true
#}
#
ifelse()
.Iteration, repeat behaviour. If we want to repeat the same command on a set of values or variables.
# for (i in 1:10) {
# print(i)
# }
i
) is automatically changing in every cycle.While statements will repeat a task until a condition is met. Can easily be infinite, so be careful.
# count <- 0
# while(count < 10) {
# print(count)
# count <- count + 1
# }
##DO NOT RUN##
# count <- 0
# while(count < 10) {
# print(count)
# count <- count - 1
# }
Useful functions: print(), browser()
for (i in 1:10) {
a <- i*2
#browser()
print(i)
}
## [1] 1
## [1] 2
## [1] 3
## [1] 4
## [1] 5
## [1] 6
## [1] 7
## [1] 8
## [1] 9
## [1] 10
Widely used functions: apply, lapply, sapply, tapply
apply()
works on 2D objects (data.frame, matrix)
iterates around rows or columns
returns vectors
dt <- data.frame(mes1=c(2,3,4), mes2=c(3,2,1), mes3=c(2,4,6))
rowmean <- apply(dt, 1, mean)
rowmean
## [1] 2.333333 3.000000 3.666667
colmean <- apply(dt, 2, mean)
colmean
## mes1 mes2 mes3
## 3 2 4
lapply()
Works on lists
Iterates around list elements
Returns a list
## [[1]]
## [1] 3
##
## [[2]]
## [1] 5
##
## [[3]]
## [1] 5
tapply()
Works on subsettable objects (e.g. vector)
Subsets them by the index and applies a function
Returns a list
One can use aggregate()
instead
## setosa versicolor virginica
## 3.4 2.8 3.0
sapply()
, vapply()
Similar to lapply
Returns a lists, matrices, vectors or arrays.
## [,1] [,2] [,3] [,4] [,5] [,6] [,7]
## [1,] 1.0 1.0 1 1.0 1.0 1.0 1
## [2,] 1.5 1.5 2 2.0 2.5 2.5 3
## [3,] 2.0 2.5 3 3.5 4.0 4.5 5
## [4,] 2.5 3.5 4 5.0 5.5 6.5 7
## [5,] 3.0 4.0 5 6.0 7.0 8.0 9
## [,1] [,2] [,3] [,4] [,5] [,6] [,7]
## Min. 1.0 1.0 1 1.0 1.0 1.0 1
## 1st Qu. 1.5 1.5 2 2.0 2.5 2.5 3
## Median 2.0 2.5 3 3.5 4.0 4.5 5
## 3rd Qu. 2.5 3.5 4 5.0 5.5 6.5 7
## Max. 3.0 4.0 5 6.0 7.0 8.0 9