【问题标题】:Narrow matrix by conditional restrictions受条件限制的窄矩阵
【发布时间】:2021-03-24 15:20:23
【问题描述】:

让我们考虑向量跟随及其组合矩阵表示:

string_vec <- c("huge", "small", "small_very", "something", "big_huge", "big_very", "tremendous", 
                "huge_big", "huge_amount", "small_amout", "else", "something_big", "something_small")
combinations <- utils::combn(string_vec, 6)

让我们定义向量

a = c("huge", big")

我现在想将我的矩阵限制为至少包含 a 的元素族中的一个元素。

即我希望至少有一个以huge 开头的元素(所以这些元素是:"huge", "huge_big", "huge_amount")和至少一个以big ("big_huge", "big_very") 开头的元素。

你知道如何获得它吗?

编辑

我发现我们可以使用applystartsWith

combinations <- combinations[,colSums(apply(combinations, 2, function(x) startsWith(x, "huge")))==1]
combinations <- combinations[,colSums(apply(combinations, 2, function(x) startsWith(x, "big")))==1]

但是我发现这个解决方案效率很低,因为我必须为每个家庭手动完成每个步骤(在更长的家庭向量中可能会很成问题)

【问题讨论】:

    标签: r arrays string matrix character


    【解决方案1】:

    我们可以paste 'a' 向量来创建单个字符串,将其用作grepl 中的pattern,循环遍历matrix 的列(base R apply)或@来自collapse 的987654327@(会更有效),检查这些列中是否有any 匹配,并使用逻辑输出对列进行子集

    library(collapse)
    out <- combinations[,dapply(combinations, FUN = 
        function(x) any(grepl(paste(a, collapse='|'), x)), MARGIN = 2)]
    

    如果我们想从'a'的所有元素中至少找到一个元素

    out <- combinations[,dapply(combinations, FUN = 
        function(x) Reduce(`&`, lapply(a, function(u) any(grepl(u, x)))), MARGIN = 2)]
    dim(out)
    #[1]    6 1555
    

    如果要检查以'a'中的那些单词开头的元素,paste^

    out <- combinations[,dapply(combinations, FUN = 
         function(x) Reduce(`&`, lapply(paste0('^', a), 
           function(u) any(grepl(u, x)))), MARGIN = 2)]
    dim(out)
    #[1]    6 1072
    

    【讨论】:

      【解决方案2】:

      使用combn 的基本 R 选项

      (cbs <- combn(string_vec, 6))[
          ,
          colSums(matrix(grepl("^huge", cbs), nrow = 6)) > 0
          & colSums(matrix(grepl("^big", cbs), nrow = 6)) > 0
      ]
      

      【讨论】:

      • 您确定此代码有效吗?我在三维情况下运行它:(cbs &lt;- combn(string_vec,3))[,colSums(matrix(grepl("^(huge|big)",cbs),nrow = 3))&gt;0]。看看最后一个元素cbs[, 286]"else" "something_big" "something_small",它不属于bighuge 系列。
      • @John 是的,我认为它有效。 ^(huge|big) 检查值是否以 hugebig 开头。
      • 是的,你是对的!我必须不正确地使用您的代码。但是,您的代码返回例如:"big_huge" "something_big" "something_small",其中不包含 huge 系列的元素。
      • @John Okey,我明白了。现在看看我的更新。
      猜你喜欢
      • 2015-07-08
      • 2021-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多