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

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


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



More information about the R-help mailing list