
Dear Berend, Mark, Jose, Arun, Great! Thank you so much for all your replies with different codings. They all work well except one - because NAs in matrix A need to take care of.   Best,Zhengyu 
 > Subject: Re: [R] Ask for help: find corresponding elements between matrix
> From: bhh@xs4all.nl
> Date: Thu, 21 Feb 2013 16:35:08 +0100
> CC: r-help@r-project.org
> To: zhyjiang2006@hotmail.com
> 
> 
> On 21-02-2013, at 15:39, JiangZhengyu <zhyjiang2006@hotmail.com> wrote:
> 
> > Dear R experts,
> > 
> > I have two matrix (seq & mat) & I want to retrieve in a new matrix all the numbers from mat that =1 (corresponding to the same row/ column position) in seq, or all the numbers in mat that =-1 in seq. - Replace all the numbers with NA if it's not 1/-1 in seq.  There are some "NA"s in seq. 
> > 
> > seq=matrix(c(1,-1,0,1,1,-1,0,0,-1,1,1,NA),3,4)
> > mat=matrix(rnorm(12),3)
> > I made this code but I don't know where's the problem..
> > 
> > seq=matrix(c(1,-1,0,1,1,-1,0,0,-1,1,1,NA),3,4)
> > mat=matrix(rnorm(12),3)
> > 
> 
> Something like this
> 
> set.seed(15)
> seq1 <- matrix(c(1,-1,0,1,1,-1,0,0,-1,1,1,NA),3,4)
> mat <- matrix(rnorm(12),3)
> ind <- which(seq1 == 1 | seq1 == -1,arr.ind=TRUE)
> m <- matrix(NA,nrow=nrow(mat),ncol=ncol(mat))
> m[ind] <- mat[ind]
> m
> 
> 
> Output is:
> 
>           [,1]       [,2]       [,3]       [,4]
> [1,] 0.2588229  0.8971982         NA -1.0750013
> [2,] 1.8311207  0.4880163         NA  0.8550108
> [3,]        NA -1.2553858 -0.1321224         NA
> 
> Berend
> 
> 
 		 	   		  
	[[alternative HTML version deleted]]

