[R] Compare rows of two matrices
Liaw, Andy
andy_liaw at merck.com
Mon Feb 21 16:21:06 CET 2005
Here's one way:
> idx <- which(! paste(l1, collapse=":") %in% paste(l2, collpase=":"))
> l1[idx,]
row col
2 1
Andy
> From: TEMPL Matthias
>
> Hello,
>
> #I have two matrices, eg.:
>
> y <- matrix( c(20, NA, NA, 45, 50, 19, 32, 101, 10,
> 22, NA, NA, 80, 49, 61, 190), ncol=4 )
> x <- matrix( c(20, NA, NA, NA, 50, 19, 32, 101, 10,
> 22, NA, NA, 80, 49, 61, 190), ncol=4 )
>
> #Whereas x contains all NA´s from y plus some additional NA´s.
> #I want to find the index of these additional NA´s. I think,
> there must be a very easy way to do this.
>
> #Here are the indices of NA´s in x and y:
> l1 <- which(is.na(x), arr.ind=TRUE)
> l2 <- which(is.na(y), arr.ind=TRUE)
>
> #> l1
> # [,1] [,2]
> #[1,] 2 1
> #[2,] 3 1
> #[3,] 4 1
> #[4,] 3 3
> #[5,] 4 3
>
> #> l2
> # row col
> #[1,] 2 1
> #[2,] 3 1
> #[3,] 3 3
> #[4,] 4 3
>
> #Now I want to find a matrix, which includes the values of
> l1, without the rows of l2,
> #which has equal entities (the index of the additional NA´S).
> #In this example the result should be row 3 of l1 with the
> values 4 and 1.
> #The following code works, but I think there must be a much
> more elegant way to do this.
>
> l3 <- l1
> l3 <- cbind( l1, rep(0, nrow(l1)) )
> num <- 1
>
> for( i in 1:nrow(l1) ){
> for( j in 1:nrow(l2) ){
> if( l1[i,1] == l2[j,1] & l1[i,2] == l2[j,2]){
> l3[i,3] <- 1
> }
> }
> }
>
> l4 <- l3[l3[,3]==0, c(1,2)]
>
> #> l4
> #row col
> # 4 1
>
> I have often such problems like this and I assume, that other
> people have similar tasks.
> My question is: Does anybody know a function in one package,
> which compares rows of two matrices like this or have anybody
> an idea to do this in a much more elegant way"?
>
> Thank you very much,
> Matthias
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
> http://www.R-project.org/posting-guide.html
>
>
More information about the R-help
mailing list