条件计算列中的最大值 [英] Conditional calculating Maximum value in the column

查看:35
本文介绍了条件计算列中的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下表:

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 方法可以是:

A base R approach could be:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆