[英]How to subset by group with dplyr
我有一個數據集,如下所示:
col1 col2
1 26
1 43
1 34
2 54
2 27
3 15
4 1
4 4
我只選擇col2大於25的那些組,因此結果數據集應為
col1 col2
1 26
1 43
1 34
2 54
2 27
這是一個示例數據集,而不是真實的數據,因此不是一個簡單的子集答案,我實際上是按照以下方式尋找dplyr答案:
Nr<-Mrd %>%
group_by(col1) %>%
slice(which.min(col2>25))
但是,此答案將使我獲得每個組中大於25的行,而不是最小為25的組。
按照您的思路,您不需要which.min
,而是min
和filter
而不是slice
df %>%
group_by(col1) %>%
filter(min(col2) > 25)
#Source: local data frame [5 x 2]
#Groups: col1 [2]
# col1 col2
# <int> <int>
#1 1 26
#2 1 43
#3 1 34
#4 2 54
#5 2 27
我們可以使用data.table
library(data.table)
setDT(df)[, if(min(col2) > 25) .SD, by = col1]
# col1 col2
#1: 1 26
#2: 1 43
#3: 1 34
#4: 2 54
#5: 2 27
或使用base R
ave
df[with(df, ave(col2>25, col1, FUN = all)),]
# col1 col2
#1 1 26
#2 1 43
#3 1 34
#4 2 54
#5 2 27
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.