[R] Add grand mean to every entry in a matrix

Gavin Simpson gavin.simpson at ucl.ac.uk
Mon Jul 13 12:55:14 CEST 2009


On Mon, 2009-07-13 at 09:06 +0000, Tom Liptrot wrote:
> Hi,
> 
> I have a matrix:
> 
> mymat <- matrix(runif(10*4), ncol=4)
> 
> I wish to subtract the column means, down the colums, subtract the row
> means from the rows and add back the grand mean - all the means should
> be the means of mymat rather than of the new matrix. 
> 
> How can I do this?
> 
> Any help much appreciated.

See ?sweep as one way to remove a set of statistics from a matrix. To
compute the statistics to sweep, you should look at ?rowMeans
and ?colMeans, plus ?mean (for the overall mean of the matrix).

The function below encapsulates the various steps that will do the
manipulation for you. I've added a conversion for the input object if it
is a data frame as mean() works differently on a matrix compared to a
df. (Your actual data is more likely to be in a data frame than a matrix
initially.)

set.seed(1)
mymat <- matrix(runif(10*4), ncol=4)

grandMean <- function(m) {
     if((df <- is.data.frame(m)))
         m <- data.matrix(m)
     rm <- rowMeans(m)
     cm <- colMeans(m)
     gm <- mean(m)
     m <- sweep(m, 1, rm, "-") # 1 means from the rows
     m <- sweep(m, 2, cm, "-") # 2 means from the cols
     m <- m + gm # here we treat m as a vector
     if(df) # return to a data.frame if one originally
         m <- as.data.frame(m)
     return(m)
}

grandMean(mymat)
grandMean(as.data.frame(mymat))

HTH

G
> 
> Thanks
> 
> Tom

-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%




More information about the R-help mailing list