Saul Garcia Saul Garcia - 2 months ago 6
R Question

Specific Ordering in R

I am making all possible combinations for a specific input, but it has to be ordered according to the order of the input aswell. Since the combinations are different sized, im struggling with the answers previously posted..

I would like to know if this is possible..

Input:

D N A 3


This means I need to output it in all combinations up to 3 character strings:

D
DD
DDD
DDN
DDA
DND
DNA
.
.


Which is basically ascending order if we consider
D<N<A


So far my output looks like this:

A
AA
AAA
AAD
AAN
AD
ADA
ADD
ADN
AN
.
.


I have tried converting the input as factor c("D","N","A") and sort my output, but then it disappears any string bigger than 1 character.

Any insight?

jav jav
Answer

Here's one possible solution:

generateCombs <- function(x, n){
  if (n == 1) return(x[1]) # Base case
  # Create a grid with all possible permutations of 0:n. 0 == "", and 1:n correspond to elements of x
  permutations = expand.grid(replicate(n, 0:n, simplify = F)) 
  # Order permutations
  orderedPermutations = permutations[do.call(order, as.list(permutations)),] 
  # Map permutations now such that 0 == "", and 1:n correspond to elements of x
    mappedPermutations = sapply(orderedPermutations, function(y) c("", x)[y + 1])
  # Collapse each row into a single string
  collapsedPermutations = apply(mappedPermutations, 1, function(x) paste0(x, collapse = ""))
  # Due to the 0's, there will be duplicates. We remove the duplicates in reverse order
  collapsedPermutations = rev(unique(rev(collapsedPermutations)))[-1] # -1 removes blank
  # Return as data frame
  return (as.data.frame(collapsedPermutations))
}

x = c("D", "N", "A")
n = 3
generateCombs(x, n)

The output is:

   collapsedPermutations
1                      D
2                     DD
3                    DDD
4                    DDN
5                    DDA
6                     DN
7                    DND
8                    DNN
9                    DNA
10                    DA
11                   DAD
...