更新时间: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)))