列中特定行的最小值和最大值

min and max for specific rows in a column

           X             Y
 1:        2          1.973203
 2:        2          1.985226
 3:        2          1.988916
 4:        2          1.998701
 5:        2          1.998701
 6:        5          4.726402
 7:        5          4.854796
 8:        5          4.891613
 9:        5          4.975043
10:        5          4.925852
11:       10          8.808622
12:       10          9.311003
13:       10          9.383758
14:       10          9.719726
15:       10          9.496574
16:       30         19.758713
17:       30         22.318520
18:       30         23.377183
19:       30         24.593082
20:       30         22.787362

你好, 我想找到每个 x 的最小值和最大值。例如,最小值和最大值为 2(即 X),最小值和最大值为 5、10 和 30。对于每个 X,Y 有 5 个值。所以,我想找到最小值和最大值以及每个 X。我是做的很长。有更简单的方法吗?谢谢!

cbind(
  setNames(aggregate(Y~X,df,min),c("X","min")),
  setNames(aggregate(Y~X,df,max)["Y"],"max")
)

   X       min       max
1  2  1.973203  1.998701
2  5  4.726402  4.975043
3 10  8.808622  9.719726
4 30 19.758713 24.593082

尝试

aggregate(. ~ X, df, range ) 

要在不同的列中显示 minmax 值,您可以执行以下操作:

library(dplyr)

df %>% group_by(X) %>%summarise(min_Y = min(Y), max_Y = max(Y)) %>% ungroup

#      X min_Y max_Y
#  <int> <dbl> <dbl>
#1     2  1.97  2.00
#2     5  4.73  4.98
#3    10  8.81  9.72
#4    30 19.8  24.6 

如果您希望值位于同一列中:

df %>% group_by(X) %>% summarise(Y = range(Y), val = c('min', 'max')) %>% ungroup

#      X     Y val  
#  <int> <dbl> <chr>
#1     2  1.97 min  
#2     2  2.00 max  
#3     5  4.73 min  
#4     5  4.98 max  
#5    10  8.81 min  
#6    10  9.72 max  
#7    30 19.8  min  
#8    30 24.6  max