[R] Constrained vector permutation
Jason Smith
devjason at gmail.com
Thu Jan 28 14:57:02 CET 2010
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))
More information about the R-help
mailing list