Hi Jason: below seems to work. you have to take the transpose because
the apply
returns the rows transposed. i'm also not sure how to make the NAs be
the last
ones but maybe someone can show us how to do that.
mat <- matrix(c(2,7,2,7,9,10,10,6,8,6,1,9,7,2,0),byrow=TRUE,nrow=3)
print(mat)
t(apply(mat,1, function(.row) {
.row[duplicated(.row)] <- NA
.row
}))
On Thu, Feb 12, 2009 at 2:31 PM, Jason Shaw wrote:
Hi,
I'm trying to take a matrix such as
[,1] [,2] [,3] [,4] [,5]
[1,] 2 7 2 7 9
[2,] 10 10 6 8 6
[3,] 1 9 7 2 0
and generate a new matrix which contains only the unique values in
each row:
[,1] [,2] [,3] [,4] [,5]
[1,] 2 7 9 NA NA
[2,] 10 6 8 NA NA
[3,] 1 9 7 2 0
My problem is that I can use apply(matrix,MARGIN=1,FUN=unique) to find
the unique values, but this leaves me with a list with arrays of
different length:
x <- apply(peaks,MARGIN=1,FUN=unique)
[[1]]
[1] 2 7 9
[[2]]
[1] 10 6 8
[[3]]
[1] 1 9 7 2 0
and using do.call("rbind",x) recycles the values of the shorter
vectors instead of filling them with NA:
do.call("rbind",x)
[,1] [,2] [,3] [,4] [,5]
[1,] 2 7 9 2 7
[2,] 10 6 8 10 6
[3,] 1 9 7 2 0
So, I'd like to either take every element of the list and extend it
with NAs to the length of the longest element, or rbind every element
where missing places are filled with NAs instead of recycled values.
Is this possible? Of course, the solution is trivial using a loop,
but I'm trying to avoid this.
Thanks for any suggestions.
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.