I just wrote a very basic function for the z tranformation in a Matrix over all columns. It looks like this:
sapply(MyObject, function(x){(x-mean(x))/sd(x)})
I randomly checked my function for some cells within the Matrix and it seems to work fine. Still I wanted to confirm the function is okay, because I’m very new to R and I could not find any good examples on the internet.
You should look at
scale()which does this for you.Your function is close to being correct; you should add
na.rm = TRUEto both thesd()andmean()function calls.I would write (if not using
scale()) the function usingsweep()instead of thesapply(). E.g.In use we have
sweepis a very useful vectorised tool for this sort of operation. Notice also thatsapply()simplifies to a matrix, which may not be what you wanted.sweep()doesn’t do this: