[R] ordering x's and y's

Bill.Venables@CMIS.CSIRO.AU Bill.Venables at CMIS.CSIRO.AU
Wed Dec 11 07:51:03 CET 2002


Robin Hankin asks below for a vectorized version of his solution below:

>  -----Original Message-----
> From: 	Robin Hankin [mailto:r.hankin at auckland.ac.nz] 
> Sent:	Wednesday, December 11, 2002 2:11 PM
> To:	arc at arcriswell.com
> Cc:	r-help at stat.math.ethz.ch
> Subject:	Re: [R] ordering x's and y's
> 
> Hi Andrew.
> 
> This was asked a few days ago (but I posted my offering offline)..
> Try:
> 
> library(gregmisc)
> do.thing2 <- function(x,y) {
>    a <- c(x,y)
>    tt <- combinations(length(a),length(x))
>    answer <- matrix(NA,nrow(tt),length(a))
>    for(i in 1:nrow(tt)) {
>      answer[i, tt[i,]] <- x
>      answer[i,-tt[i,]] <- y
>    }
> return(answer)
> }
> 
> [anyone got a vectorized version?]
	[WNV]  The original question had a single value for both x and y
with variable repititions.  I prefer to stick to this, but it could be
generalized slightly.

	library(gregmisc)
	xy.sets <- function(nx, ny, x = "x", y = "y") {
		tt <- combinations(nx + ny, nx)
		answer <- matrix(y, nrow(tt), nx + ny)
		answer[cbind(as.vector(row(tt)), as.vector(tt))] <- x
		answer
	}

	Checking:
	> xy.sets(2,3)
	      [,1] [,2] [,3] [,4] [,5]
	 [1,] "x"  "x"  "y"  "y"  "y" 
	 [2,] "x"  "y"  "x"  "y"  "y" 
	 [3,] "x"  "y"  "y"  "x"  "y" 
	 [4,] "x"  "y"  "y"  "y"  "x" 
	 [5,] "y"  "x"  "x"  "y"  "y" 
	 [6,] "y"  "x"  "y"  "x"  "y" 
	 [7,] "y"  "x"  "y"  "y"  "x" 
	 [8,] "y"  "y"  "x"  "x"  "y" 
	 [9,] "y"  "y"  "x"  "y"  "x" 
	[10,] "y"  "y"  "y"  "x"  "x" 

	The trick is the old matrix-as-index thing that surprises so many
people.

	Bill Venables.



> best
> 
> rksh
> 
> 
> 
> -- 
> 
> Robin Hankin, Lecturer,
> School of Geography and Environmental Science
> Tamaki Campus
> Private Bag 92019 Auckland
> New Zealand
> 
> r.hankin at auckland.ac.nz
> tel 0064-9-373-7599 x6820; FAX 0064-9-373-7042
> 
> as of: Wed Dec 11 17:08:00 NZDT 2002
> This (linux) system up continuously for:  468 days, 22 hours, 50 minutes
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> http://www.stat.math.ethz.ch/mailman/listinfo/r-help




More information about the R-help mailing list