[6397] in s-news-athena
unique matrix rows
daemon@ATHENA.MIT.EDU (John Wendell)
Sat Feb 4 18:55:47 1995
Date: Sat, 4 Feb 1995 13:41:40 -1000
From: John Wendell <cbaajwe@uhunix.uhcc.Hawaii.Edu>
To: s-news@utstat.toronto.edu
I am looking for a function that will return a matrix consisting of the unique
rows of a matrix, for example:
> unique.rows(matrix(c(1,2,3,2,3,4,1,2,3,4,5,6), nrow=4, byrow=T))
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 2 3 4
[3,] 4 5 6
The following function works, but I suspect there is a better way. Efficiency
is important to me because I'm using this as part of a more involved
function that will use unique.rows many times in the course of execution.
unique.rows <- function(x) {
matrix.sort.byrow <- function(x)
{
for(i in seq(ncol(x), 1, -1)) {
x <- x[order(x[, i]), ]
}
x
}
matrix.row.cut <- function(x)
{
a <- rep(T, nrow(x))
for(i in 2:nrow(x)) {
a[i] <- any(x[i - 1, ] != x[i, ])
}
x[a, , drop = F]
}
matrix.row.cut(matrix.sort.byrow(x))
}
Thanks, - John P. Wendell, University of Hawaii at Manoa.
cbaajwe@uhunix.uhcc.hawaii.edu