How to divide the elements of an array by the average of your column

4

I need to split the elements of an array by its column mean, how can I do this, is there any function to perform this simple operation?

Considering the array:

  > 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
    
asked by anonymous 11.02.2016 / 18:58

3 answers

5

This will probably solve your problem

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

The second line can be described as "Applying the function to the second dimension (columns) of the array"

== Edit ==

There is also the following option that returns the same result

sweep(A, 2, colMeans(A), "/", FALSE)
    
11.02.2016 / 20:54
1

An alternative is to replicate the averages to create an array of the same size as the original array, and then divide the original by it. The code below shows one 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
    
11.02.2016 / 19:12
1

This type of operation in arrays can be performed with the function scale , which is used to resize the columns of an array.

The default of this function is to subtract each column from its mean, then divide by the standard deviation. Since what you want is different, you have to change the arguments by supplying the vector that should be used in resizing ( scale = colMeans(A) ), and turning off centering ( 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

Do not worry about the attr that appears at the end, it's just a record of the vector used in scale, but it's ignored if you do any operation with the array later.

    
11.02.2016 / 23:03