[R] deleting invariant rows and cols in a matrix

Jonathan Baron baron at cattell.psych.upenn.edu
Sun May 12 03:17:39 CEST 2002

On 05/11/02 15:49, Patrick McKnight wrote:
>I couldn't find any existing function that would allow me to scan a
>matrix and eliminate invariant rows and columns so I have started to
>write a simple routine from scratch.  The following code fails because
>the array index goes out of bounds for obvious reasons you'll see

I'm not going to work through your example, but here is a way to
do it.  This _eliminates_ the rows and columns of matrix m1.  It
counts rows and columns as being "no variance" only in the
original matrix.  (You might imagine doing this over and over so
that all rows and columns have some variance.  That is an
exercise for the reader.)  The output is m2.

rowzeros <- apply(m1,1,sd)==0
colzeros <- apply(m1,2,sd)==0
m2 <- m1[-rowzeros,-colzeros]

If you apply this to
m1 <- matrix(c(1,1,1,1,2,3,1,4,5),3,)
you get

> m2
     [,1] [,2]
[1,]    2    4
[2,]    3    5

Jonathan Baron, Professor of Psychology, University of Pennsylvania
Home page: http://www.sas.upenn.edu/~baron
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch

More information about the R-help mailing list