簡體   English   中英

只返回 r 中一次匹配多個條件的行數

[英]return only the count of rows that match multiple criteria at once in r

我正在引用已經回答的問題,該問題使我盡可能接近: 匹配/查找基於 R 中單行中多個必需值的行

示例數據框:

test <- data.frame(grp=c(1,1,2,2,2,3,3,3,4,4,4,4,4),val=c("C","I","E","I","C","E","I","A","C","I","E","E","A"))

我修改了一個答案,只返回符合所有條件的 grp 值。

library('dplyr')
test %>%
  group_by(grp) %>%
  summarise(matching = all(c("A", "I", "C") %in% val)) %>% filter(matching ==TRUE)

從這里開始,我只需要返回符合條件的 grps 數量,作為可以粘貼到單獨數據幀的單個單元格中的單個數值。 我試圖在同一個 data.frame 上找到多組不同標准的匹配項。 (例如,符合條件 AI 和 C 的組數;符合條件 E、A 和 I 的組數;符合條件 A、I 和 E 的組數;(等等))

在示例中,它返回一個小標題:

A tibble: 1 x 2
    grp matching
  <dbl> <lgl>   
1     4 TRUE

所以有一個“grp”與確定的標准相匹配。 我需要返回那個數字:1。

如果我的標准只是字母 I,那么我希望代碼返回數字4 ,因為所有組(1、2、3 和 4)都與字母 I 匹配。

如果我的標准是字母 A,那么我希望代碼返回數字2 ,因為只有第 3 組和第 4 組與字母 A 匹配

如果我們正在尋找 'val' 的不同combnfilter ,使用combn返回一次取m = 3的 'val' 組合,按 'grp' 分組, filter 'test' 的行,其中all的組合存在於 'val' 中,通過paste 'val' 的sort unique值進行summarisepaste list綁定到具有bind_rows的單個bind_rows

library(dplyr)
combn(levels(test$val), 3, simplify = FALSE,
     FUN = function(x)
      test %>%
         group_by(grp) %>%
         filter(all(x  %in% val)) %>% 
         summarise(out = toString(sort(unique(val))))) %>% 
  bind_rows

更新

如果我們只想獲得單行為 TRUE,在根據條件filter 'grp' 后,通過將matching創建為 TRUE 進行summarise

test %>%
     group_by(grp) %>%
     filter(all(c("A", "I", "C") %in% val)) %>%
     summarise(matching = TRUE)
# A tibble: 1 x 2
#    grp matching
#  <dbl> <lgl>   
#1     4 TRUE  

或者切換summarisefilter步驟

test %>% 
   group_by(grp) %>% 
   summarise(matching = all(c("A", "I", "C") %in% val)) %>% 
   filter(matching)  %>%
   pull(matching) %>%
   sum 
#[1] 1

或者可以做得更緊湊

test %>% 
    group_by(grp) %>%
    summarise(matching = all(c("A", "I", "C") %in% val)) %>% 
    pull(matching) %>% 
    sum
 #[1] 1

或使用base R

sum(!rowSums(table(test) == 0))
#[1] 1

首先你用你的標准過濾,然后你檢查哪個組在你想要的所有字母中。 也許不是最好的方法,但它有效

criteria = c('A','I','C')
return = subset(test,test$val %in% criteria)
count = 0

for(group in unique(return$grp))
{
  criteriaSum =  sum(criteria %in% unique(return$val[return$grp == group]))
  if(criteriaSum == length(criteria))
    count = count + 1
}

暫無
暫無

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

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