dplyr filter:获取具有最小变量的行,但仅获取第一个if多个最小值

dplyr filter:获取具有最小变量的行,但仅获取第一个if多个最小值

我希望使用一种分组过滤器dplyr,在每个组中只返回具有最小变量值的行x。


我的问题是:正如预期的那样,在多个最小值的情况下,返回具有最小值的所有行。但在我的情况下,如果存在多个最小值,我只想要第一行。


这是一个例子:


df <- data.frame(

A=c("A", "A", "A", "B", "B", "B", "C", "C", "C"),

x=c(1, 1, 2, 2, 3, 4, 5, 5, 5),

y=rnorm(9)

)


library(dplyr)

df.g <- group_by(df, A)

filter(df.g, x == min(x))

正如所料,返回所有最小值:


Source: local data frame [6 x 3]

Groups: A


  A x           y

1 A 1 -1.04584335

2 A 1  0.97949399

3 B 2  0.79600971

4 C 5 -0.08655151

5 C 5  0.16649962

6 C 5 -0.05948012

使用ddply,我会以这种方式接近任务:


library(plyr)

ddply(df, .(A), function(z) {

    z[z$x == min(z$x), ][1, ]

})

......有效:


  A x           y

1 A 1 -1.04584335

2 B 2  0.79600971

3 C 5 -0.08655151

问:有没有办法在dplyr中解决这个问题?(出于速度原因)


阿波罗的战车
浏览 652回答 3
3回答

UYOU

我希望使用一种分组过滤器dplyr,在每个组中只返回具有最小变量值的行x。我的问题是:正如预期的那样,在多个最小值的情况下,返回具有最小值的所有行。但在我的情况下,如果存在多个最小值,我只想要第一行。这是一个例子:df <- data.frame(A=c("A", "A", "A", "B", "B", "B", "C", "C", "C"),x=c(1, 1, 2, 2, 3, 4, 5, 5, 5),y=rnorm(9))library(dplyr)df.g <- group_by(df, A)filter(df.g, x == min(x))正如所料,返回所有最小值:Source: local data frame [6 x 3]Groups: A&nbsp; A x&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;y1 A 1 -1.045843352 A 1&nbsp; 0.979493993 B 2&nbsp; 0.796009714 C 5 -0.086551515 C 5&nbsp; 0.166499626 C 5 -0.05948012使用ddply,我会以这种方式接近任务:library(plyr)ddply(df, .(A), function(z) {&nbsp; &nbsp; z[z$x == min(z$x), ][1, ]})......有效:&nbsp; A x&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;y1 A 1 -1.045843352 B 2&nbsp; 0.796009713 C 5 -0.08655151问:有没有办法在dplyr中解决这个问题?(出于速度原因)

红颜莎娜

只是为了完整性:这是最终dplyr解决方案,源自@hadley和@Arun的评论:library(dplyr)df.g <- group_by(df, A)filter(df.g, rank(x, ties.method="first")==1)

泛舟湖上清波郎朗

对于data.table那些可能感兴趣的人来说,这是一个解决方案:# approach with setting keysdt <- as.data.table(df)setkey(dt, A,x)dt[J(unique(A)), mult="first"]# without using keysdt <- as.data.table(df)dt[dt[, .I[which.min(x)], by=A]$V1]
打开App,查看更多内容
随时随地看视频慕课网APP