How to divide the elements of a matrix by the average of its column

Asked

Viewed 1,099 times

4

I need to divide the elements of a matrix by the respective average of its column, as I can do this, there is some function to perform this simple operation?

Considering the matrix:

  > A <- matrix(1:16, ncol = 4)
  > A
       [,1] [,2] [,3] [,4]
  [1,]    1    5    9   13
  [2,]    2    6   10   14
  [3,]    3    7   11   15
  [4,]    4    8   12   16

And the average of each column in the vector:

 > MediacolA <- colMeans(A)
 > MediacolA
 [1]  2.5  6.5 10.5 14.5

3 answers

5


It probably solves your problem

A <- matrix(1:16, ncol = 4)
apply(A, 2, function(x) x/mean(x))

The second row can be described as "Apply the function to the second dimension(columns) of the matrix"

== Edit ==

There is also the following option that returns the same result

sweep(A, 2, colMeans(A), "/", FALSE)

1

An alternative is to replicate the means to create a matrix of the same size as the original matrix, and then divide the original by it. The code below shows a way this can be done.

> A <- matrix(1:16, ncol = 4)
> MediacolA <- colMeans(A)
> repMedia <- rep(MediacolA, length(A) / length(MediacolA))
> A / t(matrix(repMedia, ncol=4))
     [,1]      [,2]      [,3]      [,4]
[1,]  0.4 0.7692308 0.8571429 0.8965517
[2,]  0.8 0.9230769 0.9523810 0.9655172
[3,]  1.2 1.0769231 1.0476190 1.0344828
[4,]  1.6 1.2307692 1.1428571 1.1034483

1

This type of die operation can be performed with the function scale, which serves precisely to resize the columns of an array.

The default of this function is to subtract each column from its average, then divide by the standard deviation. Since what you want is different, we have to change the arguments, providing the vector that should be used in resizing (scale = colMeans(A)), and disabling the centralization (center = FALSE), as follows:

> scale(A, scale = colMeans(A), center = FALSE)
     [,1]      [,2]      [,3]      [,4]
[1,]  0.4 0.7692308 0.8571429 0.8965517
[2,]  0.8 0.9230769 0.9523810 0.9655172
[3,]  1.2 1.0769231 1.0476190 1.0344828
[4,]  1.6 1.2307692 1.1428571 1.1034483
attr(,"scaled:scale")
[1]  2.5  6.5 10.5 14.5

Don’t worry about the attr which appears at the end, is just a record of the vector used in Scale, but it is ignored if you do any operation with the matrix after.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.