[R] Replacing values in a data.frame/matrix

Thaler, Thorn, LAUSANNE, Applied Mathematics Thorn.Thaler at rdls.nestle.com
Tue Mar 8 16:39:51 CET 2011


Thanks, that does the trick. I adjusted your code, such that it works
with arbitrary matrices (i.e. not only matrices which use values from
1:length(perm):

permutateValues <- function(x, perm=NULL) {
  values <- levels(as.factor(x))
  names(perm) <- values
  if (is.null(perm)) {
    perm <- sample(values)
  }
  tmp <- perm[as.numeric(as.factor(x))]
  dim(tmp) <- dim(x)
  list(x = x, perm.x = tmp, perm = perm)
}

Thanks.

> -----Original Message-----
> From: Dimitris Rizopoulos [mailto:d.rizopoulos at erasmusmc.nl]
> Sent: mardi 8 mars 2011 16:21
> To: Thaler,Thorn,LAUSANNE,Applied Mathematics
> Cc: r-help at r-project.org
> Subject: Re: [R] Replacing values in a data.frame/matrix
> 
> how about:
> 
> m <- matrix(c(1,2,3,2,1,3,3,1,2), ncol = 3, byrow = TRUE)
> perm <- c(1, 3, 2)
> 
> out <- perm[m]
> dim(out) <- dim(m)
> out
> 
> 
> I hope it helps.
> 
> Best,
> Dimitris
> 
> 
> On 3/8/2011 4:05 PM, Thaler, Thorn, LAUSANNE, Applied Mathematics
> wrote:
> > Hi all,
> >
> > Suppose we have the following matrix
> >
> > m<- matrix(c(1,2,3,2,1,3,3,1,2), ncol = 3, byrow=T)
> >
> > where in each row each number occurs only once.
> >
> > I'd like to define a permutation, e.g. 1 ->  2, 2 ->  1, 3 ->  3 and
> apply
> > it to the matrix. Thus, the following matrix should result:
> >
> > m.perm<- matrix(c(2,1,3,1,2,3,3,2,1), ncol = 3, byrow=T)
> >
> > i.e. each 1 should map to 2 and vice verse while 3 maps to itself.
> What
> > I've done so far is:
> >
> > permutateMatrix<- function(mat, perm=NULL) {
> >    values<- 1:NCOL(mat)
> >    if (is.null(perm)) {
> >      perm<- sample(values)
> >    }
> >    newmat<- replace(mat, sapply(values, function (val)
> which(mat==val)),
> >        rep(perm, each=NROW(mat)))
> >    return(list(mat.perm=newmat, perm=perm))
> > }
> >
> > "perm" is the permutation vector: 1 maps to the first element of
> perm, 2
> > to the second and so on. Thus, for the example we would use
> >
> > perm<- c(2,1,3)
> > all.equal(m.perm, permutateMatrix(m, perm)$mat.perm) # TRUE
> >
> > What do you think of this solution? Are there more elegant ways of
> doing
> > that? Any comments appreciated.
> >
> > Thanks + BR,
> >
> > Thorn
> >
> > ______________________________________________
> > 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.
> >
> 
> --
> Dimitris Rizopoulos
> Assistant Professor
> Department of Biostatistics
> Erasmus University Medical Center
> 
> Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
> Tel: +31/(0)10/7043478
> Fax: +31/(0)10/7043014
> Web: http://www.erasmusmc.nl/biostatistiek/



More information about the R-help mailing list