The function apply() is certainly one of the most useful function. I was scared of it during a while and refused to use it. But it makes the code so much faster to write and so efficient that we can't afford not using it. If you are like me, that you refuse to use apply because it is scary, read the following lines, it will help you. You want to know how to use apply() in general, with a home-made function or with several parameters ? Then, go to see the following examples.




The function apply() is known as extremely useful to improve the speed of our code when we want to operate some functions on a matrix or a vector. I use it, but I do not really know how to use it.

What is it?

apply() is a R function which enables to make quick operations on matrix, vector or array. The operations can be done on the lines, the columns or even both of them.

How does it work?

The pattern is really simple : apply(variable, margin, function).
-variable is the variable you want to apply the function to.
-margin specifies if you want to apply by row (margin = 1), by column (margin = 2), or for each element (margin = 1:2). Margin can be even greater than 2, if we work with variables of dimension greater than two.
-function is the function you want to apply to the elements of your variable.

Because I think example is clearer than anything else, here is the most important example to understand the function apply().


Introduction:

#the matrix we will work on:
a = matrix(c(1:15), nrow = 5 , ncol = 3)

#will apply the function mean to all the elements of each row
apply(a, 1, mean)
# [1]  6  7  8  9 10

#will apply the function mean to all the elements of each column
apply(a, 2, mean)
# [1]  3  8 13

#will apply the function mean to all the elements of each column and of each row, ie each element
apply(a, 1:2, mean)
#     [,1] [,2] [,3]
# [1,]    1    6   11
# [2,]    2    7   12
# [3,]    3    8   13
# [4,]    4    9   14
# [5,]    5   10   15

We have just worked on the different margins to show the basic possibilities. But as I said we can also work on other variables such as an array of dimension 3:

#apply() for array of other dimension :
a = array(1:8, dim = c(2,2,2))
apply(a, 3, sum)

# , , 1
#
#       [,1] [,2]
# [1,]    1    3
# [2,]    2    4
#
# , , 2
#
#        [,1] [,2]
# [1,]    5    7
# [2,]    6    8


Use a home-made function:

We can also use our own function. For example, we reproduce the function sum (absolutely useless but let's keep it simple!).

f1 = function(x){
  return(sum(x))
}

apply(a, 1, f1)

Several parameters:
A function with several parameters. Here is the main reason why I was never using apply(), I did not know how to do when I had several parameters in a function. This is quite simple, we just have to specifiy in the parameter the variable which is constant.


f2 = function(x1,x2){
  x1-x2
}
b = 2

#with the second parameter as an option
apply(a,1,f2,x2=b)

#       [,1] [,2] [,3] [,4] [,5]
# [1,]   -1    0    1    2    3
# [2,]    4    5    6    7    8
# [3,]    9   10   11   12   13
# [3,]   22   24   26   28   30

#with the first parameter as an option
apply(a,1,f2,x1=b)

# [,1] [,2] [,3] [,4] [,5]
# [1,]    1    0   -1   -2   -3
# [2,]   -4   -5   -6   -7   -8
# [3,]   -9  -10  -11  -12  -13

I hope these examples will help you. Personally I use the function apply() since I went through these few examples. Of course there are many other details which can be useful, but these first examples deal with the main useful possibilities of apply().
1

View comments

The financial market is not only made of stock options. Other financial products enable market actors to target specific aims. For example, an oil buyer like a flight company may want to cover the risk of increase in the price of oil.

I found a golden website. The blog of Esteban Moro. He uses R to work on networks. In particular he has done a really nice code to make some great videos of networks. This post is purely a copy of his code. I just changed a few arguments to change colors and to do my own network.

3

As you have certainly seen now, I like working on artificial neural networks. I have written a few posts about models with neural networks (Models to generate networks, Want to win to Guess Who and Study of spatial segregation).

1

I already talked about networks a few times in this blog. In particular, I had this approach to explain spatial segregation in a city or to solve the Guess Who? problem. However, one of the question is how to generate a good network.

The function apply() is certainly one of the most useful function. I was scared of it during a while and refused to use it. But it makes the code so much faster to write and so efficient that we can't afford not using it.

1

Have you ever played the board game "Guess who?".

If you want to choose randomly your next holidays destination, you are likely to process in a way which is certainly biased. Especially if you choose randomly the latitude and the longitude.

4

My previous post is about a method to simulate a Brownian motion. A friend of mine emailed me yesterday to tell me that this is useless if we do not know how to simulate a normally distributed variable.

The Brownian motion is certainly the most famous stochastic process (a random variable evolving in the time). It has been the first way to model a stock option price (Louis Bachelier's thesis in 1900).

1

The merge of two insurance companies enables to curb the probability of ruin by sharing the risk and the capital of the two companies.

For example, we can consider two insurance companies, A and B.

How to estimate PI when we only have R and the formula for the surface of a circle (Surface = PI * r * r)?

The estimation of this number has been one of the greatest challenge in the history of mathematics. PI is the ratio between a circle's circumference and diameter.

I was in a party last night and a guy was totally drunk. Not just the guy who had a few drinks and speaks a bit too loud, but the one who is not very likely to remember what he has done during his night, but who is rather very likely to suffer from a huge headache today.

I am currently doing an internship in England. Therefore, I keep alternating between French and English in my different emails and other forms of communication on the Internet. I have been surprised to see that some websites are able to recognize when I use French or when I use English.

The VIX (volatility index) is a financial index which measures the expectation of the volatility of the stock market index S&P 500 (SPX). The higher is the value of the VIX the higher are the expectations of important variations in the S&P 500 during the next month.

The Olympic Games have finished a couple of days ago. Two entire weeks of complete devotion for sport. Unfortunately I hadn’t got any ticket but I didn’t fail to watch many games on TV and internet.

Hello (New World!), 

My name is Edwin, I’m a 22 year-old French student in applied mathematics. In particular, I study probability, statistics and risk theory.

Blog Archive
Translate
Translate
Loading