R:成组的最小值或最大值 [英] R: group-wise min or max

查看:94
本文介绍了R:成组的最小值或最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于如何使用SQL获取分组最小或最大值的文章很多.但是,您如何在R中做到这一点?

There are so many posts on how to get the group-wise min or max with SQL. But how do you do it in R?

比方说,您已经获得了以下数据框

Let's say, you have got the following data frame

ID | t | value
a | 1 | 3
a | 2 | 5
a | 3 | 2
a | 4 | 1
a | 5 | 5
b | 2 | 2
b | 3 | 1
b | 4 | 5

对于每个ID,我都不需要最小值,而是最小值的值.

For every ID, I don't want the min t, but the value at the min t.

ID | value
a | 3
b| 2

推荐答案

df是您的data.frame-

df is your data.frame -

library(data.table)

setDT(df) # convert to data.table in place

df[, value[which.min(t)], by = ID]

输出-

> df[, value[which.min(t)], by = ID]
   ID V1
1:  a  3
2:  b  2

这篇关于R:成组的最小值或最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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