且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何仅按组将具有最低和最高值的行保留在特定列中?

更新时间:2023-01-20 19:28:40

我们可以将 slice which.min / which.max 按用户分组后

We can use slice with which.min/which.max after grouping by 'user'

library(dplyr)
df1 %>%
   group_by(user) %>%
   slice(c(which.min(value), which.max(value)))
#   id  user value
#  <dbl> <dbl> <dbl>
#1     1     1     1
#2     3     1     5
#3     4     2     2
#4     6     2     9






或者另一个选择是 arrange 切片。按用户分组后,排列将值按升序排列,每个用户和切片的第一个最后一行


Or another option is arrange with slice. After grouping by 'user', arrange the 'value' in ascending for each 'user' and slice the first and last row

df1 %>% 
     group_by(user) %>%
     arrange(value) %>% 
     slice(c(1, n()))






如果存在最小值和/或最大值'值'并且想要保留所有 min max 行,请使用 filter


If there are ties for min and/or max 'value' and wanted to keep all the min and max rows, use filter

df1 %>%
     group_by(user) %>% 
     filter(value %in% c(min(value), max(value)))