[R] deleting invariant rows and cols in a matrix

Jonathan Baron baron at cattell.psych.upenn.edu
Sun May 12 22:16:13 CEST 2002


>On 05/11/02 15:49, Patrick McKnight wrote:
>>Greetings,
>>
>>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
>>shortly.

Turns out my original idea didn't work, so I also figured out how
to do it recursively so that you get a matrix with no invariant
rows and columns, even if the invariant ones arise after deleting
other ones.  The function is mcyc, below.  Probably more
complicated than needed, but it works.

---------

mtest <- function(m1)
{
rowzeros <- apply(m1,1,sd)==0
colzeros <- apply(m1,2,sd)==0
m2 <- m1[rowzeros==F,colzeros==F]
d <- sum(dim(m1)-dim(m2))
return(m2,d)
}

mcyc <- function(m2)
{
m3 <- mtest(m2)
while(m3$d!=0) {m2 <- m3$m2;m3 <- mtest(m2)}
return(m3$m2)
}

-------
For example:

> mcyc(matrix(c(1,1,1,1,4,3,1,2,2,4,4,4),3,))
[1] 4 3
-- 
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