簡體   English   中英

grepl 和 group_by 使用 dplyr 在 R 中進行匯總

[英]grepl and group_by to summarise in R using dplyr

我有一個 dataframe:

region_calls = data.frame(
  samples = c("S1", "S2", "S3", "S1", "S2", "S3"),
  CN_Region = c("A","A","A", "B", "B", "B"), 
  CN_State = c("0", "NoCall1or2", "1", "2", "NoCall1or2", "NoCall")
)

我試圖這樣做:

region_calls %>% group_by(CN_Region) %>%
  summarise(call_rate = sum(grepl("0|NoCall_1or2|1|NoCall_2or3|2|3|NoCall_3or4|4", CN_State)/n()),
            fixed_call_rate = sum(grepl("0|1|2|3|4", CN_State)/n()))

但是每個區域都給出相同的call_ratefixed_call_rate

預期的答案是:

預期答案

基本上,我從分子中排除NoCall (不是NoCall1or2 ),而不是從分母中的n()

我錯過了什么? 我還在分母中嘗試nrow(.) 我看到了一些類似的問題,但他們分別處理grepl而不是我打算的。 也歡迎任何更清潔的dplyr方法。

對於call_rate ,我們可以計算沒有"NoCall"的值的比率。 call_rate不需要正則表達式,因為它是完全匹配而不是模式匹配。 對於fixed_call_rate ,我們使用grepl來查找其中只有數字的值的比率。 我們為其添加單詞邊界( \\b ),使其僅匹配"1""2"等而不"NoCall1or2"

library(dplyr)

region_calls %>%
  group_by(CN_Region) %>%
  summarise(call_rate = mean(CN_State != "NoCall"),
            fixed_call_rate = mean(grepl('\\b\\d\\b', CN_State)))

#  CN_Region call_rate fixed_call_rate
#  <fct>         <dbl>           <dbl>
#1 A             1               0.667
#2 B             0.667           0.333

我們也可以使用data.table

library(data.table)
setDT(region_calls)[, .( call_rate = mean(CN_State != "NoCall"),
        fixed_call_rate = mean(grepl('\\b\\d\\b', CN_State))), CN_Region]

暫無
暫無

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

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