[R] Writing a Permutation Function

David Winsemius dwinsemius at comcast.net
Sat Apr 28 15:55:02 CEST 2012


On Apr 28, 2012, at 9:18 AM, mlell08 wrote:

>>
>> On Apr 28, 2012, at 8:11 AM, petermec <petermec at buffalo.edu> wrote:
>>
>>> 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?
>>>
> Rownames can be assigned by using rownames(dataframe) <- c("Row1",
> "Row2", etc.)
> The Wikipedia article about 'Permutation' holds some commonly used
> Algoritms, perhaps you can find some inspiration there?
>

You should be able to use the 'duplicated' function to remove  
duplicates by prepending its value with "!". Unlike 'make.unique',  
'duplicated' is designed for working with objects having dimensions.

-- 

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list