R, much like any language, has the capacity for looping/iterating. This means that we can work over a sequence of objects, performing operations, appending values etc.
In R, loops can be declared like so:

However, if you try and run this code, it may take some time. This is because loops are not very efficiently implemented in R, and there is a good reason.
R has a function called “apply” which is the preferred way of implementing looping. It can seem a bit weird at first so let’s examine how the function works.
The apply function is used to execute some functions on a matrix or vector. Since R utilizes mostly vectors and matrices, this works out well, hence why the apply is preferred over for loops.
The apply syntax is really simple actually:
apply(<variable>, margin,<function> )
Where variable is your variable (matrix or vector), margin is whether it should be operating on rows or columns (or both), and function is the function you want to use.
Let’s take a look at it in action:

In addition to apply, there exists several other similar functions for different data structures:
- lapply; for performing operations on lists
- sapply; for applying a function to each element of a vector, list of dataframe

Now we’ll look at conditionals, so that we can make our code do different things. Much like other languages, R has the classic IF/ELSE constructs:

You can see that the syntax of R is really quite similar to that of Python, especially if you’ve been following the Python series on the blog.
It is also possible to create your own functions in R, which can be useful for generating data points or for plotting mathematical functions. To create a function in R, the following syntax is used:

It is important to remember that R is dependent on the curly braces for defining blocks of code, unlike in Python where the indentation determines the block of the code.
Lastly, we’ll try and apply a function we’ve created to some vector.
And this has completely replaced the loop functionality and executed much quicker.
Next time
Next time we will be looking at reading in data from files, performing PCA and scaling/regularization on data.