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]]