Apply
apply() applies a function to each row or column of a matrix.
# matrix 2x10
m <- matrix(c(1:10, 11:20), nrow = 10, ncol = 2)
# this sums rows values:
apply(m, 1, sum)
## [1] 12 14 16 18 20 22 24 26 28 30
# this sum column values:
apply(m, 2, sum)
## [1] 55 155
lapply() applies a function to each element of a list.
# list where is a and b element
my_list <- list(a = 1:10, b = 2:20)
# calculate mean of each list elements:
lapply(my_list, mean)
## $a
## [1] 5.5
##
## $b
## [1] 11
sapply() is more user friendly version of lapply and will return a list of matrix where appropriate.
# calculating mean
sapply(my_list, mean)
## a b
## 5.5 11.0
# what type is result?
class(sapply(my_list, mean))
## [1] "numeric"
mapply() is more or less a multivariate version of sapply. It applies a function to all corresponding elements of each argument.
tapply() applies a function to subsets of a vector.
tapply(mtcars$hp, mtcars$cyl, FUN = sum)
## 4 6 8
## 909 856 2929
by applies a function to subsets of a data frame
replicate() is an extremely useful function to generate datasets for simulation purposes. The final argument turn the result into a vector or matric if possible.
replicate(10, rnorm(10), simplify = TRUE )
## [,1] [,2] [,3] [,4] [,5] [,6]
## [1,] -1.4036653 -0.2410946 0.3749349 1.48155532 -0.1027756 0.1266945
## [2,] 1.7618949 -0.2876565 0.2667836 -0.58081225 0.5947887 0.9335372
## [3,] 0.5918905 2.2328522 0.1952886 0.56116675 1.0244861 0.4478738
## [4,] 0.6120719 2.0435606 -0.5423690 -0.01757601 1.7608420 1.3131877
## [5,] -1.3132832 0.3534599 2.1618018 -0.29148902 -0.7394857 -0.2890967
## [6,] 0.3423450 0.9266935 -0.8680827 0.98919269 0.6950112 -0.4495551
## [7,] -0.1034184 -0.8147407 0.8069193 -0.81572324 0.7283151 0.8521975
## [8,] 0.6088360 -0.9746051 1.7905596 -0.45408937 -0.5467834 -1.3761973
## [9,] 0.2460124 -0.1346001 -0.3536862 -0.18009448 0.3803184 0.3885687
## [10,] 0.6478928 0.5722962 -0.2944561 -1.26958025 0.8248690 -0.1079098
## [,7] [,8] [,9] [,10]
## [1,] 0.44205957 1.4048126 0.8437445 0.8988182
## [2,] 0.09833495 0.6802951 -1.2639912 -1.6790651
## [3,] 0.43408102 -0.1379448 0.9864896 -0.5217732
## [4,] -0.47644506 0.1855462 0.0364129 -0.1049269
## [5,] -0.02589849 2.0991884 -0.5774630 2.0435193
## [6,] -1.59299779 -1.2346848 -0.2972403 -0.7864043
## [7,] -0.95846129 2.0368645 -0.2122265 -1.3576049
## [8,] 1.72201604 -1.4632958 0.6328692 -0.7297649
## [9,] -0.91480124 0.9210964 -1.3353671 -0.1029382
## [10,] 0.31595732 -0.9925505 -0.5596720 -1.1850906
Loops
For-loop runs all values in a vector.
for(valuutta in c("euro","dollari","peso")){
print(valuutta)
}
## [1] "euro"
## [1] "dollari"
## [1] "peso"
Simple for-loop that print ten times “Hello”.
for (i in 1:4){
print("Hello")
}
## [1] "Hello"
## [1] "Hello"
## [1] "Hello"
## [1] "Hello"
Same loop using while-loop
i = 1
while(i < 4){
print("Hello")
i = i + 1
}
## [1] "Hello"
## [1] "Hello"
## [1] "Hello"