[R] replacing elements in matrix: fastest method?

Prof Brian Ripley ripley at stats.ox.ac.uk
Sat Aug 4 10:44:33 CEST 2001


On Sat, 4 Aug 2001, Agustin Lobo wrote:

> I replace some elements of a matrix a
>
> > a
>      [,1] [,2] [,3]
> [1,]    1    2    3
> [2,]    4    5    6
> [3,]    7    8    9
> [4,]   10   11   12
>
> according to a reclassification matrix such
>
> > pares
>      [,1] [,2]
> [1,]    1    2
> [2,]    5    6
> [3,]    8    7
>
> to get
>
> > b
>      [,1] [,2] [,3]
> [1,]    1    2    3
> [2,]    4    5    6
> [3,]    7    8    9
> [4,]   10   11   12

Um, b <- a would be as fast as anything (since .Alias `does not exist').


> As both a and pares can be very large, I'd like to know the
> fastest way for this operation in R. I'm using:
>
> a[which(a%in%pares[,1])]<-pares[,2]
>
> and
>
> replace(a,which(ima%in%pares[,1]),pares[,2])

1) that throws away its result, and
2) a <- replace(a,which(ima%in%pares[,1]),pares[,2]) is a long-winded way
to do the first.


> Is there any preference in terms of speed
> and/or R style? Is there another, better way?

The preference is for correct solutions: a fast answer to the wrong
problem is of negliglible use.

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.

-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

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