[R] Odp: Combine two matricies

Petr PIKAL petr.pikal at precheza.cz
Mon Jul 13 11:48:12 CEST 2009


Hi

matrix is virtually a vector so you can find index of values of x and add 
those values to propper places in ax

ax <- a
idx <- which(!is.na(x))
ax[idx] <- x[idx]
ax
     [,1] [,2] [,3]
[1,]    3    2    1
[2,]    4    2    2
[3,]    5    5    2

Regards
Petr

r-help-bounces at r-project.org napsal dne 13.07.2009 11:31:12:

> 
> Hi,
> 
> I have two matricies a and x:
> 
> a<-matrix(c(3,4,5,2,3,4,1,1,2), nrow=3, ncol=3)
> 
>  [,1] [,2] [,3]
> [1,]    3    2    1
> [2,]    4    3    1
> [3,]    5    4    2
> 
> x<-matrix(c(3, NA, NA, NA, 2, 5, NA, 2, 2), nrow=3, ncol=3)
> 
>  [,1] [,2] [,3]
> [1,]    3   NA   NA
> [2,]   NA    2    2
> [3,]   NA    5    2
> 
> I wish to combine these two into one matrix using the values from x 
where x 
> has values, and values from a where x has NA's, giving a new matrix 
which 
> would look like this:
> 
> ax<-matrix(c(3,4,5,2,2,5,1,2,2), nrow=3, ncol=3)
> 
>     [,1] [,2] [,3]
> [1,]    3    2    1
> [2,]    4    2    2
> [3,]    5    5    2
> 
> I want an automatic way of doing this as my actual application is a much 
larger matrix.
> 
> Thanks in advance
> 
> Tom
> 
> 
> _________________________________________________________________
> 
> [[elided Hotmail spam]]
> 
> 
>    [[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at 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.




More information about the R-help mailing list