September 2018
Beginner
206 pages
4h 27m
English
For loops are often used to go through every column or row of a dataframe in R.
Say, for example, that we're interested in the mean of all of the numeric columns of the built-in iris dataset (which is four out of the five—everything but the Species column, which is a factor variable of character strings indicating the species of each iris.) We could type, four times, mean(iris$Sepal.Length), with each input variable name changing each time. However, a far more efficient way to complete this exercise would be to use a for loop.
If we simply want to print the means to the console, we could use a for loop as follows:
for(i in seq_along(iris)){print(mean(iris[[i]]))}
The output will be as follows:
We'll come back to the output, especially ...
Read now
Unlock full access