[R] Writing a Permutation Function

petermec petermec at buffalo.edu
Sat Apr 28 14:11:45 CEST 2012


Hi everyone, 

I am somewhat new to R and I am trying to write a permutation function such
that it inputs a character vector and from an arbitrary length "n" which is
the length of the combinations for the character vector. I know there are R
packages for permutation but this is for an assignment.

So far this is what I have:

alphabet = c("a","b","c","d")
spot = c()
permute = function(alphabet,n){
for (i in 1:factorial(length(alphabet))){
    perm = sample(alphabet, replace=F, size=n)
    spot = rbind(spot, perm, deparse.level=2)
}
print(spot)
}

This function works but it has some flaws for what I need. I would like the
print output to have the rownames as the combination of the characters for
each row (ie aa for "a" "a"). Also, this code is producing duplicate
combinations whereas I only want an output of unique combinations.

To address the rownames problem I have, I have been trying to meddle around
with creating a dataframe from rbind with something like:
data2 = data.frame(spot, check.names=TRUE) 

I was thinking something along the lines of this to remove duplicates:
or something like make.unique(spot)
or make.names(spot, unique=TRUE)

Neither of these have been working for me. Could someone help point me in
the right direction?

Much appreciated.


--
View this message in context: http://r.789695.n4.nabble.com/Writing-a-Permutation-Function-tp4594621p4594621.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list