Andrew Rominger <ajrominger <at> gmail.com> writes:

> I'm trying to permute a vector of positive integers > 0 with the constraint

Hi Andy

I'm not sure if you are explicitly wanting to use a sampling approach, but the 
gtools library has a permutations function (found by ??permutation then ?
gtools::combinations).

Hope this helps,
Jason Smith

Here is the script I used:


# Constraint
# f(n_i) <= 2 * f(n_(i-1))
#
# Given a start value and the number of elements
# recursively generate a vector representing the 
# maximum values each index is allowed
#
f <- function(value, num_elements) {
        #cat(paste("f(",value,",",num_elements,")\n"))
        if (num_elements < 1) {
                value;
        } else {
                z <- c(value,f(2*value, num_elements-1))
        }
}

# Generate base vector
v <- 2:6

# Calculate constraint vector
v.constraints <- f(v[1],length(v)-1)

# Generate permutations using gtools functions
library(gtools) 
v.permutations <- permutations(length(v), length(v), v)

# Check each permutation
results <- apply(v.permutations,1, function(x) all(x <= v.constraints))

#
# Display Results
#
print("Original Vector")
print(v)
print("Constraint Vector")
print(v.constraints)
print("Does Vector meet Constraints")
print(cbind(v.permutations,results))

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to