如何分组并获得具有X max的Y列的值? [英] How to group by and get the value for column Y having X max?
本文介绍了如何分组并获得具有X max的Y列的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个以前从未遇到过的用例。我有以下数据框,并希望选择值 y,其中 x分别针对条件 i的每个级别达到其最小值和最大值。
I have an use-case that I have not came across before. I have the following data frame and would like to select values of "y" where "x" achieves its minimum and maximum respectively for each level of the condition "i".
> library(dplyr)
> df <- data.frame(i=c(1,1,2,2),x=c(1.0,2.0,3.0,4.0),y=c('a','b','c','d'))
> ddply(df, .(i), summarise, Min=min(x), Max=max(x))
i Min Max
1 1 2
2 3 4
这是正确的,但我想使用 y
其 x
是 Min
或 Max
。
which is correct but I'd like to instead have the y
whose x
is Min
or Max
.
i Min Max
1 a b
2 c d
我该怎么做?
推荐答案
library(plyr)
df <- data.frame(i=c(1,1,2,2),x=c(1.0,2.0,3.0,4.0),y=c('a','b','c','d'))
ddply(df, .(i), summarise, Min=y[which.min(x)], Max=y[which.min(x)])
这篇关于如何分组并获得具有X max的Y列的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文