Re(2): [R] replacing elements in matrix: fastest method?

Agustin Lobo alobo at ija.csic.es
Sat Aug 4 19:12:42 CEST 2001


On Sat, 4 Aug 2001, Prof Brian Ripley wrote:

> I believe *both* of yours are erroneous.
> 
> I guess you wanted to replace the entries in `a' which match column 1 of
> pares by the corresponding item in column 2.  But you didn't say: *please*
> tell us what you are trying to do rather than ask for comments on
> `solutions'.  Also, I will assume you want this for a numeric array.
> 
> However, your first solution will only work if each element of pares[,1]
> occurs exactly once in `a' in the order specified (which happens to be
> true for your example).  Rather, you need something like
> 
> m <- match(a, pares[, 1], 0)
> a[m > 0] <- pares[m, 2]
> 
> If we knew what the problem really was, we might be able to solve it
> efficiently, but for now we are only guessing.
> 

Your guess is correct. I clarify my question:
I want to replace values in a matrix (a) according to  
reclassification rules that are stated
in a 2-columns matrix (pares) in which the values to
be replaced are in the first column and the
replacing values are in the second column.

As B. Ripley notes, the 2 methods that I was trying

> a[which(a%in%pares[,1])]<-pares[,2]
>
> and
>
> replace(a,which(ima%in%pares[,1]),pares[,2])

work only if there are no repeated values
in a, as in the example. As the general
case implies repeated values in matrix a
(length(unique(a)) <= length(a)), the
method suggested by Prof. Ripley 

m <- match(a, pares[, 1], 0)
a[m > 0] <- pares[m, 2]

is great help. Thanks.

Agus

Dr. Agustin Lobo
Instituto de Ciencias de la Tierra (CSIC)
Lluis Sole Sabaris s/n
08028 Barcelona SPAIN
tel 34 93409 5410
fax 34 93411 0012
alobo at ija.csic.es




-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list