Find lowest date in each group [duplicate]

2019-09-11 12:46发布

问题:

This question already has an answer here:

  • Subset data based on Minimum Value 2 answers

Hi there: I'm trying to find the lowest date in each group. The purpose is to find what date is common to each of several time series. Currently the data look like this.

library(tidyr)
library(dplyr)
grouping_variable<-sample(c('a', 'b', 'c'), 500, replace=TRUE)
date<-sample(seq(as.Date('1999/01/01'), as.Date('2015/01/01'), by="day"), 500)
numeric_variable<-rnorm(500, 50, sd=2)
df<-data.frame(grouping_variable, date, numeric_variable)

And my working attempt is basically this.

df %>%
group_by(grouping_variable)%>%
min(date)

回答1:

We can use slice

 df %>% 
    group_by(grouping_variable) %>% 
    slice(which.min(date))