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

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 zero and std. deviation 1, I've to transpose t(z.mat) again. Am I making some silly mistake somewhere?

Thanks

PCA R matrix • 38k views
ADD COMMENT
2
Entering edit mode
the prcomp() method provides an option to scale your data. You dont have to scale "yourself"
ADD REPLY
7
Entering edit mode
10.2 years ago
Michael 55k

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.

ADD COMMENT
3
Entering edit mode
10.2 years ago
Ahill ★ 2.0k

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

ADD COMMENT

Login before adding your answer.

Traffic: 1861 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6