Assuming you have no background in programming and just want to know how to use the for loop. I have created a very simple data-frame and will do something easy.
I want to have the sum of each row in the data-frame (luckily we also have the apply family to do this simply).
df <- data.frame(x=c(1,4,2,6,7,1,8,9,1),
y=c(4,7,2,8,9,1,9,2,8))
This is the example shown everywhere, which is highly unsatisfactory.
for(i in 1:10){
print(i)
}
Only print the example of the sum of each row.
for(i in 1:nrow(df)){
print(df$x[i]+df$y[i])
}
This is the part often horrible explained everywhere (I do not get why? Perhaps I just used the wrong searching terms/keywords?). Fortunately, there was a good example here on Stack Exchange that showed me how. So, the credits go to someone else. Yet, this part is fairly easy, but for someone with no background in modeling, R, or any programming what so ever, it can be an pain in the ass to figure out. To make a for loop and store the results, you NEED to create an object that can store the data of the loop.
Here a simple for loop storing the results in a data frame.
loopdf <- as.data.frame(matrix(ncol = 1, nrow = 0))
for(i in 1:nrow(df)){
loopdf[i,] <- df$x[i]+df$y[i]
}
loopdf
Here a simple for loop storing the results in a list.
looplist <- list()
for(i in 1:nrow(df)){
looplist[[i]] <- df$x[i]+df$y[i]
}
do.call(rbind, looplist)
Here a loop concatenating the results in an atomic vector.
loopvec <- NULL
for(i in 1:nrow(df)){
loopvec <- c(loopvec, df$x[i]+df$y[i])
}
loopvec
Here the apply loop (two versions).
apply(df, 1, sum)
apply(df, 1, function(x), sum(x))