## 16.1 Example: Control structures and loops

# If Argument
x <- -5
x
if(x <= 0) {y <- 1} else {y <- 0}
y

# If Argument
x <- 1
if(x == 0 | x == 1) {y <- 1} else {y <- 0}
y

# If Argument
x <- 10
if(x<= -10 &  x>= 10) {y <- 1} else {y <- 0}
y
# Warum ist y hier gleich 0?!? BUG?
# Used in complicated loops, e.g. to give names
# conditional on some variable having some name!

# For Loop
for (x in 1:10) print(sqrt(x)) # is ok because of single line

# For Loop
x <- 0
for(i in 1:10){
x <- x+i
print(x)
} # x steigt mit an

swiss2 <- swiss
rownames(swiss2) <- NULL
vars <- names(swiss2)
for(i in vars){
# x <- x+i
print(i)
print(class(swiss2[,i]))
swiss2[,i][1] <- NA
} # x steigt mit an

# SKIP

# While Loop
x <- 0
while(x<13) {
x <- x+1
print(x)
} # solange x<13=TRUE

#Repeat Loop
x <- 0
repeat{x <- x+1; print(x); if(x>=10) break} # repeat that until x>=10 is TRUE

# Process data with loops
for (column in 2:6) { # this loop runs through 2 to 6
print(names(swiss)[column])
print(mean(swiss[,column]))
}

# Could be all sorts of object classes, e.g. you could loop over several data sets

for (dataset in c(data1, data2, data3)) {
# Do something, e.g. data cleaning, calculations, model estimations etc.
}

# But: Most loops are avoidable and there are more efficient ways to deal with your specific problem. E.g. with functions from dplyr, sapply(), ave() or specialized functions like rowMeans(), colMeans(), colSums() etc.

# Think about your problem and look for better solutions. If loops are necessary: Pull as much code out of the loop as possible. Avoid all functions that use data frames (cbind(), rbind(), data.frame()) within the loop. Use vectors and matrices instead.