簡體   English   中英

受條件限制的窄矩陣

[英]Narrow matrix by conditional restrictions

讓我們考慮向量跟隨及其組合矩陣表示:

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 的元素族中的a元素。

即我希望至少有一個以huge開頭的元素(所以這些元素是: "huge", "huge_big", "huge_amount" )和至少一個以big ("big_huge", "big_very")

你知道如何獲得它嗎?

編輯

我發現我們可以使用apply with startsWith

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

但是我發現這個解決方案效率很低,因為我必須為每個家庭手動完成每個步驟(在較長的家庭向量中,這可能會非常有問題)

我們可以paste “a”向量來創建單個字符串,將其用作grepl中的pattern ,循環遍歷matrix的列( base R apply )或從collapse中應用dapply (會更有效),檢查是否有any匹配在這些列中,並使用邏輯 output 對列進行子集

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

使用組合的基本combn選項

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM