过滤组内的行

Filtering rows within a group

我有如下数据框:

ID <- c(1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5)
Type <- c('A','B','C','B', 'C','A','B', 'C','A','C', 'C')
Value <- c(10, 11, 12, 1, 2, 100, 101, 102, -1, -2, -10)

df <- data.frame(ID, Type, Value)

我的目标是一个数据框,每个 ID 只有一行。但我想 select 基于某些标准/瀑布原理的行。

所以首选 A 型,然后是 B 型,然后是 C 型。我的目标是以下数据框:

ID <- c(1, 2, 3, 4, 5)
Type <- c('A','B','A','A', 'C')
Value <- c(10, 1, 100, -1, -10)

df_goal <- data.frame(ID, Type, Value)

我想先转为宽格式,然后再使用 dplyr::coalesce,但随后我会松开类型列。我很确定有一个使用 dplyr::group_bydplyr::summarise 的解决方案。最初我还考虑过在 dplyr::filter 语句中使用 dplyr::if_else,但我认为这是不可能的。

感谢任何帮助!

dplyr中使用slice_min,默认情况下按变量排序的组过滤最小值(这里Type,按字母顺序排序)。

library(dplyr)
df %>% 
  group_by(ID) %>% 
  slice_min(Type)

# A tibble: 5 × 3
# Groups:   ID [5]
     ID Type  Value
  <dbl> <chr> <dbl>
1     1 A        10
2     2 B         1
3     3 A       100
4     4 A        -1
5     5 C       -10

在基础 R 中:

df[with(df, Type == ave(Type, ID, FUN = min)), ]

data.table解决方案

library(data.table)

setDT(df) # make it a data.table if it is not yet

setkey(df, Type) # set the key on Type
df[, .SD[1L], by = ID] # subset the first value per ID

#    ID Type Value
# 1:  1    A    10
# 2:  3    A   100
# 3:  4    A    -1
# 4:  2    B     1
# 5:  5    C   -10