Hi, I guess this is what you wanted: seq1<-matrix(c(1,-1,0,1,1,-1,0,0,-1,1,1,NA),3,4) seq1 # [,1] [,2] [,3] [,4] #[1,] 1 1 0 1 #[2,] -1 1 0 1 #[3,] 0 -1 -1 NA
set.seed(15) mat1<-matrix(rnorm(12),3) mat1 # [,1] [,2] [,3] [,4] #[1,] 0.2588229 0.8971982 0.0227882 -1.0750013 #[2,] 1.8311207 0.4880163 1.0907732 0.8550108 #[3,] -0.3396186 -1.2553858 -0.1321224 -0.3649801 m<-sapply(seq_len(ncol(mat1)),function(i) ifelse(seq1[,i]==1|seq1[,i]==-1,mat1[,i],NA)) m # [,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 A.K. ----- Original Message ----- From: JiangZhengyu <zhyjiang2...@hotmail.com> To: r-help@r-project.org Cc: Sent: Thursday, February 21, 2013 9:39 AM Subject: [R] Ask for help: find corresponding elements between matrix 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) m=rep(NA,nrow(seq)) for(i in 1:nrow(seq)) {m[i]=mat[seq[i]==1] } Error in m[i] = mat[seq[i] == 1] : replacement has length zero In addition: Warning message: In m[i] = mat[seq[i] == 1] : number of items to replace is not a multiple of replacement length > I was wondering if anyone can help me with this. Thanks in advance, Zhengyu eg. here is what I want > head(seq) [,1] [,2] [,3] [,4] [1,] 1 1 0 1 [2,] -1 1 0 1 [3,] 0 -1 -1 NA > head(mat) [,1] [,2] [,3] [,4] [1,] 0.1006950 0.3354360 0.1796888 1.3198761 [2,] 1.0948252 0.5350797 -0.5739454 0.2744478 [3,] -0.5409936 -0.3820084 -0.5601096 0.9239680 This is a new new matrix. > head(mat1) [,1] [,2] [,3] [,4] [1,] 0.1006950 0.3354360 NA 1.3198761 [2,] NA 0.5350797 NA 0.2744478 [3,] NA NA NA NA [[alternative HTML version deleted]] ______________________________________________ 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.