Thaler, Thorn, LAUSANNE, Applied Mathematics
2011-Mar-08 15:05 UTC
[R] Replacing values in a data.frame/matrix
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
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/