有条件的计算列中的最大值 [英] Conditional calculating Maximum value in the column
本文介绍了有条件的计算列中的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有下表:
Class x2 x3 x4
A 14 45 53
A 8 18 17
A 16 49 20
B 78 21 48
B 8 18 5
我需要为每个类(A和B)在 X3列中找到最大值,保留该行并删除其他行。
I need for each "Class" (A and B) find the maximum value in column "X3", keep that row and delete other rows.
输出应采用以下格式:
Class x2 x3 x4
A 14 49 20
B 78 21 48
请问我问题中是否有不清楚的地方。
Please, ask me questions if something unclear in my problem.
谢谢!
推荐答案
基本的R方法可能是:
mydf[as.logical(with(mydf, ave(x3, Class, FUN = function(x) x == max(x)))), ]
# Class x2 x3 x4
# 3 A 16 49 20
# 4 B 78 21 48
但是,请注意,如果 max
有多个值,它将返回多个行
However, note that if there are multiple values tied for max
, it would return multiple rows for that group.
以下是一种可能的 data.table方法:
Here's a possible "data.table" approach:
library(data.table)
setkey(as.data.table(mydf), Class, x3)[, tail(.SD, 1), by = Class]
# Class x2 x3 x4
# 1: A 16 49 20
# 2: B 78 21 48
这篇关于有条件的计算列中的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文