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

Uwe Ligges ligges at statistik.uni-dortmund.de
Tue Sep 17 21:57:10 CEST 2002


Rob Lee wrote:
> 
> 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?

What about vectorized indexing as common in S? For example swapping rows
m and n of a matrix A:  
  A[c(m, n), ] <- A [c(n, m), ]

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