s-news
[Top] [All Lists]

Re: permutation

To: "'s-news@lists.biostat.wustl.edu'" <s-news@lists.biostat.wustl.edu>
Subject: Re: permutation
From: Tim Hesterberg <timh@insightful.com>
Date: 14 Apr 2005 15:05:25 -0700
In-reply-to: <51E9450E2DA1D4118DB400508BF9AC34169EDE7A@kenmsg32.schp.com> (larisa.reyderman@spcorp.com)
References: <51E9450E2DA1D4118DB400508BF9AC34169EDE7A@kenmsg32.schp.com>
Larisa Reyderman asked:
>I have a seemingly easy question.  I need to create a matrix consisting of
>all possible permutations of the following vector:
>
>0.5  1.0  1.5  2.0  3.0  4.0  5.0  6.0  8.0 10.0 12.0 16.0

Below is a function to compute permutations of 1:n.  Use
        matrix(x[permutations(length(x))], length(x))
for your task.

Michael Conklin wrote:
>If you get any good answers please share them ...
>for generating permutations and combinations of a
There is a "combinations" function in library(resample) (see bottom).

permutations <- function(n){
  # Compute all n! permutations from 1:n
  # Return matrix with n rows and factorial(n) columns.
  if(n < 1)
    return(matrix(numeric(0), 0, 0))
  result <- matrix(1, 1, 1)
  if(n == 1)
    return(result)
  f <- function(j, result){
    # result = permutations(n) for an earlier n.
    # j      = an integer between 1 and n+1.
    # Return a matrix with j in the first row, and n additional
    # rows taken from result, but modified to skip j.
    result[result >= j] <- result[result >= j] + 1
    rbind(j, result)
  }
  for(i in 2:n){
    result <- do.call("cbind",
                     lapply(1:i, f, result = result))
  }
  dimnames(result) <- NULL
  result
}

========================================================
| Tim Hesterberg       Research Scientist              |
| timh@insightful.com  Insightful Corp.                |
| (206)802-2319        1700 Westlake Ave. N, Suite 500 |
| (206)283-8691 (fax)  Seattle, WA 98109-3012, U.S.A.  |
|                      www.insightful.com/Hesterberg   |
========================================================
Download the S+Resample library from www.insightful.com/downloads/libraries


<Prev in Thread] Current Thread [Next in Thread>