Loop Menggunakan Apply Family Function

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

bentuk dari apply menunjukkan dapat melakukan pengulangan ttanpa membuat syntax loop

  1. apply
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
  1. lapply
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
  1. sapply
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
  1. vapply
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
  1. tapply
groups<-as.factor(rbinom(32, n=5, prob = 0.4))
tapply(groups, groups, length)
## 11 12 13 15 
##  1  2  1  1
#####