[R] Compare matrices

Rolf Turner r.turner at auckland.ac.nz
Mon Jan 19 22:05:07 CET 2009


On 20/01/2009, at 9:48 AM, Andrej Kastrin wrote:

> Dear all,
>
> Suppose that I have a matrix A
>
>     A <- matrix(c(3,3,3,3,3,3,3,3,3),3,3)
>
> and a logical matrix B
>
>     B <- matrix(c(T,T,T,F,T,T,F,T,F),3,3)
>
> The result  matrix should be
>
>     C <- matrix(c(3,3,3,NA,3,3,NA,3,NA),3,3)
>
> Is there any simple tip or trick to perform this without looping?

(a) It is helpful to state a clear question rather than expecting the
reader to infer from an example just what your question is.

(b) It is advisable to use TRUE and FALSE as the values of a logical
variate, rather than T and F.  The former are reserved words, the latter
are not, which can cause all hell to break loose.

(c) You are wasting a good many key strokes.  You could simply say

	A <- matrix(3,3,3)

(d) I infer that what you want is for C to equal A where B is TRUE
and NA otherwise.  One way to accomplish this is:

	C <- matrix(,3,3)
	C[B] <- A[B]

		cheers,

			Rolf Turner

######################################################################
Attention:\ This e-mail message is privileged and confid...{{dropped:9}}




More information about the R-help mailing list