Sweeping through data in R

Today I came across a data set which showed the revenue split by product and location. The data was formated to show only the split by product for each location and the overall split by location, similar to the example in the table below.

Revenue by product and continent

Africa

America

Asia

Australia

Europe

A

40%

30%

50%

40%

40%

B

20%

40%

20%

30%

40%

C

40%

30%

30%

30%

20%

Total

10%

40%

20%

10%

20%

I wanted to understand the revenue split by product and location. Hence, I have to multiply the total split by continent for each product in each column. Or in other words I would like to use the total line and sweep it through my data. Of course there is a function in base R for that. It is called sweep. To my surprise I can’t remember that I ever used sweep before. The help page for sweep states that it used to be based on apply, so maybe that’s how I would have approached those tasks in the past.

Anyhow, the sweep function requires an array or matrix as an input and not a data frame. Thus let’s store the above table in a matrix.

Now I can sweep through my data. The arguments for sweep are the data set itself (in my case the first three rows of my matrix), the margin dimension (here 2, as I want to apply the calculations to the second dimension / columns), the summary statistics to be applied (in my case the totals in row 4) and the function to be applied (in my scenario a simple multiplication "*"):