Condicionais e loops
# -----------------------------------------------------------------------------
# Loop for:
# -----------------------------------------------------------------------------
vari = 0
for(i in 1:5){
vari[i] = i
}
vari
## [1] 1 2 3 4 5
vv = list()
for(i in 1:5){
vv[[i]] = i
}
vv
## [[1]]
## [1] 1
##
## [[2]]
## [1] 2
##
## [[3]]
## [1] 3
##
## [[4]]
## [1] 4
##
## [[5]]
## [1] 5
meudados = data.frame(v1=rnorm(100),
v2=rnorm(100),
v3=rnorm(100),
v4=rnorm(100))
medias = NULL
#De um modo restrito
for(i in 1:4){
medias[i] = mean(meudados[,i])
names(medias)[i] = names(meudados)[i]
}
#De um modo mais amplo, generalizado
for(i in 1:ncol(meudados)){
medias[i] = mean(meudados[,i])
names(medias)[i] = names(meudados)[i]
}
medias
## v1 v2 v3 v4
## 0.07570056 -0.03693063 -0.09143181 -0.12431440
# -----------------------------------------------------------------------------
# Loop while:
# -----------------------------------------------------------------------------
z = 0
while(z < 5) {
z = z + 2
print(z)
}
## [1] 2
## [1] 4
## [1] 6
# -----------------------------------------------------------------------------
# Loop repeat:
# -----------------------------------------------------------------------------
z = 0
repeat{
z = z + 2
print(z)
if(z > 4){
break()
}
}
## [1] 2
## [1] 4
## [1] 6