[R] Common R/S Idioms - Swapping Rows or Cols in a Matrix
Giovanni Petris
GPetris at uark.edu
Wed Sep 18 00:27:34 CEST 2002
I would try something like
> A[c(s,r),] <- A[c(r,s),]
Giovanni
--
__________________________________________________
[ ]
[ Giovanni Petris GPetris at uark.edu ]
[ Department of Mathematical Sciences ]
[ University of Arkansas - Fayetteville, AR 72701 ]
[ Ph: (479) 575-6324, 575-8630 (fax) ]
[ http://definetti.uark.edu/~gpetris/ ]
[__________________________________________________]
> 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