contoh pemodelan looping
sub_iris <- iris[,-5]
a<- rep(NA, 4)
for(i in 1: length(sub_iris)){
a[i]<-mean(sub_iris[,i])
}
a
## [1] 5.843333 3.057333 3.758000 1.199333
berikut adalah beberapa fungsi dari apply family
apply():fungsi generik yang diaplikasijan fungsi kepada kolom atau baris pada matrix
lapply(): bekerja pada jenis data list dan memebrikan ouput berupa data list juga
sapply():bentuk sederhana dari lapply yang menghasilkan output matrix
vapply(): verified apply
tapply(): tagged apply
bentuk dari apply menunjukkan dapat melakukan pengulangan ttanpa membuat syntax loop
x<- cbind(x1 = 3, x2 = c(4:1, 2:5))
x
## x1 x2
## [1,] 3 4
## [2,] 3 3
## [3,] 3 2
## [4,] 3 1
## [5,] 3 2
## [6,] 3 3
## [7,] 3 4
## [8,] 3 5
x<- list(a = 1:10, beta = exp(-3:3), Logic = c(TRUE,FALSE,TRUE, FALSE))
x
## $a
## [1] 1 2 3 4 5 6 7 8 9 10
##
## $beta
## [1] 0.04978707 0.13533528 0.36787944 1.00000000 2.71828183 7.38905610
## [7] 20.08553692
##
## $Logic
## [1] TRUE FALSE TRUE FALSE
x<- list(a = 1:10, beta = exp(-3:3), Logic = c(TRUE,FALSE,TRUE, FALSE))
sapply(x, FUN = mean)
## a beta Logic
## 5.500000 4.535125 0.500000
x<-sapply(3:9, seq)
x
## [[1]]
## [1] 1 2 3
##
## [[2]]
## [1] 1 2 3 4
##
## [[3]]
## [1] 1 2 3 4 5
##
## [[4]]
## [1] 1 2 3 4 5 6
##
## [[5]]
## [1] 1 2 3 4 5 6 7
##
## [[6]]
## [1] 1 2 3 4 5 6 7 8
##
## [[7]]
## [1] 1 2 3 4 5 6 7 8 9
groups<-as.factor(rbinom(32, n=5, prob = 0.4))
tapply(groups, groups, length)
## 13 14 16 17
## 1 2 1 1
#####