So this is a basic for-loop, which just prints out the values.
data <- cbind(1:10);
for (i in 1:nrow(data)) {
print(i)
}
If you want to save the output you have to initialize a vector / list /matrix, etc.:
output <- vector()
for (i in 1:nrow(data)) {
k[i] <- i
}
k
And a little example for nested loops:
data <- cbind(1:5);
data1 <- cbind(15:20)
data2 <- cbind(25:30)
for (i in 1:nrow(data)) {
print(paste("FOR 1: ", i))
for (j in 1:nrow(data1)) {
print(paste("FOR 2: ", j))
for (k in 1:nrow(data2)) {
cat(paste("FOR 3: ", k, "\n"))
}
}
}
But as already mentioned, you would probably be better of using an "apply"-function (apply, sapply, lapply, etc). Check out this post: Apply-Family
Or using the package dplyr with the pipe (%>%) operator.
To include some if/else-synthax in the loop:
data <- cbind(1:5);
data1 <- cbind(15:20)
data2 <- cbind(25:30)
for (i in 1:nrow(data)) {
if (i == 1) {
print("i is 1")
} else {
print("i is not 1")
}
for (j in 1:nrow(data1)) {
print(paste("FOR 2: ", j))
for (k in 1:nrow(data2)) {
cat(paste("FOR 3: ", k, "\n"))
}
}
}
In the first loop, I am asking if i is 1.
If yes, the first print statement is used ("i is 1"), otherwise the second is used ("i is not 1").