如何根据R数据框中的另一列对包含最大值的行进行子集化?

要根据 R 数据框中的另一列对包含最大值的行进行子集化,我们可以按照以下步骤操作 -

  • 首先,创建一个包含一个数字列和一个分类列的数据框。

  • 然后,使用带有 max 函数的 tapply 函数来查找基于另一列的数值列中包含最大值的行。

示例 1

创建数据框

让我们创建一个数据框,如下所示 -

x<-rnorm(20)
factor1<-sample(LETTERS[1:4],20,replace=TRUE)
df1<-data.frame(x,factor1)
df1

执行时,上述脚本生成以下内容output(this output will vary on your system due to randomization)-

输出结果

      x    factor1
1 -1.21231516 A
2 -0.01576519 B
3 0.59032593 D
4 -0.41583339 C
5 -0.38508102 A
6 -0.61177209 C
7 -0.52961795 C
8 0.30561837 A
9 -0.58067776 A
10 0.62246173 C
11 -0.58479709 C
12 0.09817433 B
13 1.11240042 C
14 0.29007306 B
15 -0.66345792 B
16 -1.80789902 A
17 0.33419804 C
18 -0.15665767 A
19 1.56775923 C
20 1.49345799 B

根据另一列查找包含最大值的行

例子

使用 tapply 函数根据 df1 中的 factor1 列查找 x 列中的最大行数 -

x<-rnorm(20)
factor1<-sample(LETTERS[1:4],20,replace=TRUE)
df1<-data.frame(x,factor1)
tapply(df1$x,df1$factor1,max)

输出

      A          B       C       D
0.3056184 1.4934580 1.5677592 0.5903259

示例 2

创建数据框

让我们创建一个数据框,如下所示 -

y<-sample(1:50,20)
factor2<-sample(c("Low","Medium","High"),20,replace=TRUE)
df2<-data.frame(y,factor2)
df2

执行时,上述脚本生成以下内容output(this output will vary on your system due to randomization)-

输出

y factor2
1 45 Low
2 2 Medium
3 5 High
4 33 Low
5 28 High
6 37 Medium
7 7 High
8 21 High
9 48 Low
10 18 High
11 15 High
12 38 High
13 20 Medium
14 4 Low
15 22 Medium
16 34 Low
17 32 Low
18 29 Low
19 24 High
20 17 Medium

根据另一列查找包含最大值的行

例子

使用 tapply 函数根据 df2 中的 factor2 列查找 y 列中的最大行数 -

tapply(df2$y,df2$factor2,max)

输出

High Low Medium
38 48 37