R: Scaling the rows of a matrix
2
1
Entering edit mode
7.2 years ago
The ▴ 160

I'm facing a problem while scaling(z-transform) the row values of a numeric gene expression data matrix to be used for a PCA analysis. Here's a to generate a toy matrx of 6 samples and 20 genes:

  rm(list=ls())
set.seed(12345)
my.mat <- matrix(rnorm(120,0,0.5),nrow=6,byrow=TRUE)
rownames(my.mat) <- paste("s",1:6,sep="")
colnames(my.mat) <- paste("g",1:20,sep="")
dim(my.mat)
# 6 20#six rows 20 columns
z.mat <- apply(my.mat, MARGIN = 1, FUN = scale )
dim(z.mat)
#20 6 # The matrix gets transposed##!!!!

to get the correct matrix for which all the row means equal zeo and std. deviation 1, I've to transpose t(z.mat) again. Am I making some silly mistake somewhere?

Thanks

R matrix PCA • 27k views
2
Entering edit mode
the prcomp() method provides an option to scale your data. You dont have to scale "yourself"
7
Entering edit mode
7.2 years ago

from ?scale

scale is generic function whose default method centers and/or scales the columns of a numeric matrix.

You do not need to use apply, scale(t(my.mat)) will do the same.

3
Entering edit mode
7.2 years ago
Ahill ★ 1.9k

No, this is documented R behaviour. See ?apply:

If each call to FUN returns a vector of length n, then apply returns an array of dimension c(n, dim(X)[MARGIN]) if n > 1