[R] deleting invariant rows and cols in a matrix
Patrick McKnight
pem at theriver.com
Sun May 12 22:35:27 CEST 2002
Jon,
Thanks greatly. Yes, I tried to implement your first solution but the
returned matrix was NULL. I will use your solution below and try Chuck
Cleland's solution and send back a note to the list which one was most
efficient. Thanks for taking the time to help me with this problem.
BTW, Chuck's solution was to use the following code:
mymat[which(apply(mymat, 1,var) > 0), which(apply(mymat, 2, var) > 0)]
and then, of course, I would need a loop to ensure that no new rows or
columns were invariant after deleting the rows/cols in each round.
Thanks again.
Cheers,
Patrick
On Sun, 2002-05-12 at 13:16, Jonathan Baron wrote:
> >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
--
Cheers,
Patrick
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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