【问题标题】:How to generate all permutations of lists of string?如何生成字符串列表的所有排列?
【发布时间】:2023-03-04 14:06:02
【问题描述】:

我有这样的字符数据

[[1]]
[1] "F" "S"

[[2]]
[1] "Y" "Q" "Q"

[[3]]
[1] "C" "T"

[[4]]
[1] "G" "M"

[[5]]
[1] "A" "M"

我想为每个单独的列表(不在列表之间混合)生成所有排列,并将它们组合成一个大列表。

例如,对于第一个和第二个列表,即"F" "S""Y" "Q" "Q",我想得到排列列表为c("FS", "SF")c("YQQ", "QYQ", "QQY"),然后将它们合并为一个。

【问题讨论】:

  • 数据是列表列表还是向量列表?如果您包含一些代码来生成示例数据,这将有助于我们更好地理解。例如:X <- list(c("F","S"), c("Y", "Q", "Q"))

标签: r string list character permutation


【解决方案1】:
library(combinat)

final <- unlist(lapply(X , function(test_X) lapply(permn(test_X), function(x) paste(x,collapse='')) ))

【讨论】:

    【解决方案2】:

    看起来您想要的输出与此相关帖子 (Generating all distinct permutations of a list in R) 不完全相同。但我们可以在那里建立答案。

    library(combinat)
    
    # example data, based on your description
    X <- list(c("F","S"), c("Y", "Q", "Q"))
    
    result <- lapply(X, function(x1) {
        unique(sapply(permn(x1), function(x2) paste(x2, collapse = "")))
    })
    
    print(result)
    

    输出

     [[1]]
     [1] "FS" "SF"
    
     [[2]]
     [1] "YQQ" "QYQ" "QQY"
    

    第一个(外部)lapply 遍历列表的每个元素,其中包含单个字母(在向量中)。在每次迭代中,permn 获取单个字母(例如“F”和“S”),并返回具有所有可能排列的列表对象(例如“F”“S”和“S”F”)。如您所描述的输出,内部sapply 采用每个排列并将它们折叠成单个字符值,过滤为唯一值。

    【讨论】:

      【解决方案3】:

      这是combinat::permn 的一种方法:

      library(combinat)
      lapply(data,function(x)unique(sapply(combinat::permn(x),paste,collapse = "")))
      #[[1]]
      #[1] "FS" "SF"
      #
      #[[2]]
      #[1] "YQQ" "QYQ" "QQY"
      #
      #[[3]]
      #[1] "CT" "TC"
      #
      #[[4]]
      #[1] "GM" "MG"
      #
      #[[5]]
      #[1] "AM" "MA"
      
      

      或与 unlist 一起使用:

      unlist(lapply(data,function(x)unique(sapply(combinat::permn(x),paste,collapse = ""))))
      # [1] "FS"  "SF"  "YQQ" "QYQ" "QQY" "CT"  "TC"  "GM"  "MG"  "AM"  "MA" 
      

      数据:

      data <- list(c("F", "S"), c("Y", "Q", "Q"), c("C", "T"), c("G", "M"), 
          c("A", "M"))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-13
        • 1970-01-01
        • 2011-02-06
        • 2010-09-11
        • 2018-01-03
        • 1970-01-01
        • 2012-05-17
        相关资源
        最近更新 更多