【问题标题】:R - Permutations with conditionsR - 有条件的排列
【发布时间】:2021-11-07 11:12:26
【问题描述】:

我对 R 比较陌生,我一直在寻找我的问题的答案,但没有运气。 希望你能帮助我。

这是到目前为止我写的代码:

    #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)

我想查看所有可能的排列/组合,但有一些限制,这就是我迷路的地方。 我需要在 V1 和 V2 中只有“come_in-blatt-1”和“come_in-blatt-2”。 对于所有其他 V3、V4 直到 V11(在这种情况下 -> r = 11),将只是“come_in-front-1”和“come_in-front-2”。

有没有办法让 R 告诉我这个? 到目前为止,我已经打开 Excel 并过滤掉了我不需要的内容,但现在我遇到的问题是列表比 Excel 可以处理的要大。 :-/

谢谢。

【问题讨论】:

  • V1-V11 是从哪里来的?我在你的代码中没有看到。
  • 也许这就是你需要的? pastebin.com/unphCs0Z如果是,我会在SO上发布答案。
  • 嗨@MarcoSandri,感谢您的帮助。差不多就是这样,这是我对您的代码所做的更改: filt_rule

标签: r combinations permutation


【解决方案1】:

如果我了解 blatt 选项可以在 V1V2 中,这是一种方法。

#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

【讨论】:

  • 嗨科尔,是的,你理解正确。感谢您的解决方案。 “gtools”来自旧版本是否有问题,或者我应该使用新功能?谢谢
  • 不,没有问题。我删除了它以消除任何混乱。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多