Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

r - How to get rows, by group, of data frame with earliest timestamp?

df <- data.frame(group=c(1,2,4,2,1,4,2,3,3),
             ts=c("2014-02-13","2014-06-01","2014-02-14","2014-02-11","2013-02-01","2014-02-02","2014-03-21","2014-12-01","2014-02-11"),
             letter=letters[1:9])
df$ts <- as.Date(df$ts,format='%Y-%m-%d')

I want to find an operation that will produce the complete rows containing the minimum timestamp per group, in this case,

group         ts letter
    1 2013-02-01      e
    4 2014-02-02      f
    2 2014-02-11      d
    3 2014-02-11      i

A quick and dirty (and slow) base R solution would be

dfo <- data.frame(df[order(df$ts,decreasing=F),],index=seq(1:nrow(df)))
mins <- tapply(dfo$index,dfo$group,min)
dfo[dfo$index %in% mins,]

Intuitively, I think if there was a way to add an order index by group then I could just filter to where that column's value is 1, but I'm not sure how to execute it without lots of subsetting and rejoining.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use dplyr

library(dplyr)
group_by(df, group) %>% summarise(min = min(ts), letter = letter[which.min(ts)]) 
#   group        min letter
# 1     1 2013-02-01      e
# 2     2 2014-02-11      d
# 3     3 2014-02-11      i
# 4     4 2014-02-02      f

You could also slice the ranked rows

group_by(df, group) %>% 
    mutate(rank = row_number(ts)) %>% 
    arrange(rank) %>%
    slice(1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...