Dividing each cell value by its column mean

gianmarco

TS Contributor
#1
Hello,
it should be an easy task but I am experiencing an issue.

As per title, I want to divide each cell of the crosstabulation by its column mean. I provide some reproducible example.

This is a small dataset:
C-like:
mydata <- structure(list(none = c(4, 4, 25, 18, 10), light = c(2, 3, 10,
24, 6), medium = c(3, 7, 12, 33, 7), heavy = c(2, 4, 4, 13, 2
)), row.names = c("SM", "JM", "SE", "JE", "SC"), class = "data.frame")
Code:
   none light medium heavy
SM    4     2      3     2
JM    4     3      7     4
SE   25    10     12     4
JE   18    24     33    13
SC   10     6      7     2
Now the code to divide the cell values by the column mean:
C-like:
newtable <- data / apply(data, 2, mean)
These are the column means
Code:
none  light medium  heavy
  12.2    9.0   12.4    5.0
new table:
Code:
        none     light    medium     heavy
SM 0.3278689 0.2222222 0.2419355 0.4000000
JM 0.4444444 0.2419355 1.4000000 0.3278689
SE 2.0161290 2.0000000 0.9836066 0.4444444
JE 3.6000000 1.9672131 3.6666667 1.0483871
SC 0.8196721 0.6666667 0.5645161 0.4000000
In the above, some values are ok, some others are wrong.
For instance, the value in the cell in the 2nd row 1st column (0.4444) should be the same as in the cell above it (coz they both stem from 4 / 12.2), yet the value is different.

I got any clue as to why this is happening.

Gm
 

Dason

Ambassador to the humans
#2
It cycles through the rows in column 1 first. So if your data is called a and your mean vector is called m it would do a[1,1]/m[1] then a[2,1]/m[2] then a[3,1]/m[3] then a[4,1]/m[4] then recycle the mean vector to give a[5,1]/m[1].

You could use the sweep function to do what you want.

Code:
> m <- colMeans(mydata)
> m
  none  light medium  heavy
  12.2    9.0   12.4    5.0
> sweep(mydata, 2, m, FUN = "/")
        none     light    medium heavy
SM 0.3278689 0.2222222 0.2419355   0.4
JM 0.3278689 0.3333333 0.5645161   0.8
SE 2.0491803 1.1111111 0.9677419   0.8
JE 1.4754098 2.6666667 2.6612903   2.6
SC 0.8196721 0.6666667 0.5645161   0.4
 
Last edited: