[R] Ask for help: find corresponding elements between matrix
Berend Hasselman
bhh at xs4all.nl
Thu Feb 21 16:35:08 CET 2013
On 21-02-2013, at 15:39, JiangZhengyu <zhyjiang2006 at 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
More information about the R-help
mailing list