[19017] in s-news-athena

home help back first fref pref prev next nref lref last post

[S] Summary : Removing Rows from a matrix

daemon@ATHENA.MIT.EDU (Brian A Millen.)
Mon Aug 23 20:36:04 1999

Message-Id: <3.0.6.32.19990823202924.007ba570@stat.ohio-state.edu>
Date: Mon, 23 Aug 1999 20:29:24 -0400
To: s-news@wubios.wustl.edu
From: "Brian A Millen." <millen.2@osu.edu>
Mime-Version: 1.0
Content-Type: text/plain; charset="us-ascii"


MY ORIGINAL MESSAGE:

>I want to remove a row from a matrix if it is the reverse of a row
>"earlier" in the matrix.  For example, if I have the following matrix, X:
>
>Row1: (1,2,3,4)
>Row2: (1,3,2,4)
>Row3: (4,3,2,1)
>Row4: (3,2,4,1)
>Row5: (3,2,1,4)
>Row6: (4,2,3,1)
>
>I want to apply a function to X so that I am left with the matrix, Y:
>
>Row1: (1,2,3,4)
>Row2: (1,3,2,4)
>Row3: (3,2,4,1)
>Row4: (3,2,1,4)
>
>Note: since  X[3,] == rev(X[1,]) and  X[6,] == rev(X[2,]), the rows X[3,]
>and X[6,] are not included in the matrix Y.
>
>Thank you, in advance, for any help you may give.
>

THE RESPONSES:

Bill Dunlap submitted the following code for a function f to remove the
rows from the matrix.  

>f<- function(X)
>	{
>        	if(!is.data.frame(X))
>                	X.cols <- split(X, col(X))
>        	else X.cols <- X
>        	x <- do.call("paste", c(list(sep = ","), X.cols))
>        	y <- do.call("paste", c(list(sep = ","), rev(X.cols)))
>        	i <- match(x, y)
>        	X[is.na(i) | i > seq(along = x),  ]
>	}
>

In addition, David Bowie submitted code that would perform the desired
operation.  This code, like that above, uses the paste function to create
vectors that will then be compared via the match function.

>dimnames(x) <- list(NULL,as.character(1:ncol(x)))
>revname <-
>
as.character(-sort(-eval(parse(text=paste("c(",paste(dimnames(x)[[2]],collap
se=","),")",sep="")))))
>y <- x[,revname] 

>xs <- apply(x,1,function(x)paste(x, collapse = ","))[x[,1] <=x[,ncol(x)]]
>ys <- apply(y,1,function(x)paste(x, collapse = ","))[!(x[,1]<=x[,ncol(x)])]

>new.x <- rbind(x[x[,1] <= x[,ncol(x)],],x[!(x[,1] <=
>  x[,ncol(x)]),][is.na(match(ys,xs)),])
>


Brian

-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu.  To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message:  unsubscribe s-news

home help back first fref pref prev next nref lref last post