Search code examples
rcombinationspermutation

R - Permutations with conditions


I am relatively new to R, and I have searched for an answer to my Problem, but without luck. Hope that you can Help me.

This is so far the code that I have written:

    #load library
    library(gtools)
    
    #the Options
    my_list <- c("come_in-blatt-1",
                 "come_in-blatt-2",
                 "come_in-front-1",
                 "come_in-front-2"
                 )
    
    #get all permutations
    result <- permutations(n = 4 , r = 11, v = my_list,repeats.allowed=T)
    
    #save as:
    write.csv(result, file = "result-test3.csv")
    
    #open as CSV file
    
    command <- paste("open excel", file = "result-test3.csv")

    system(command)

I want to see all possible permutations/combinations there are, but with some constraints, and here is where I am lost. I need that in V1 and V2 there will just be "come_in-blatt-1" and "come_in-blatt-2". For all others V3, V4 until V11 (in this case -> r = 11), will be just "come_in-front-1" and "come_in-front-2".

Is there a way to make R show me this? Until now I have opened Excel and filtered out what I don`t needed, but now I have the problem that the list is bigger than that what excel can work with. :-/

Thanks.


Solution

  • Here is one approach if I understand the blatt options can be in either V1 or V2.

    #load library
    library(gtools)
    
    ## Create V1:V2 perms separately from V3:V11
    blatts = permutations(n = 2, r = 2, v = c("come_in-blatt-1", "come_in-blatt-2"), repeats.allowed = TRUE)
    fronts = permutations(n = 2, r = 9, v = c("come_in-front-1", "come_in-front-2"), repeats.allowed = TRUE)
    
    ## Combine the two
    ## For each row of blatts, repeat the matrix and combine with fronts
    res = lapply(seq_len(nrow(blatts)),
                 function(i){
                   cbind(blatts[rep(i, nrow(fronts)), ],
                         fronts)
                   })
    
    ## combine the list into one
    res = do.call('rbind', res)
    
    ## look at the dim of the resulting matrix
    dim(res)
    #> [1] 2048   11
    
    ## verify the work 
    all(res[, 1:2] %in% c("come_in-blatt-1", "come_in-blatt-2"))
    #> [1] TRUE
    all(res[, 3:11] %in% c("come_in-front-1", "come_in-front-2"))
    #> [1] TRUE