[R] Common R/S Idioms - Swapping Rows or Cols in a Matrix

Rob Lee rlee at fpcc.net
Tue Sep 17 18:47:19 CEST 2002


Is there an idiomatic way of swapping rows/cols in a Matrix?

The standard approach for swapping rows r and u:
tmpRow = A[r,]
A[r,] = A[u,]
A[u,] = tmpRow

Robin Hankin (R-Octave help sheet maintainer) says:

[I would implement your three line solution (which works!) as follows:

swap <- function(a,m,n) {
 tmp <- a[m]
 a[m] <- a[n]
 a[n] <- tmp
 return(a)
}

then use things like

x <- matrix(1:100,10,10)

x[ swap(1:10,5,6),]                #swaps rows  5&6
x[,swap(1:10,5,6) ]                #swaps cols  5&6
x[ swap(1:10,5,6),swap(1:10,5,6)]  #both together

]

Anybody?

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