简体   繁体   中英

Finding the minimum value of a variable for each value of another variable in R

I'm fairly new to R and am trying to find the minimum date/time for each value of an ID number. Below is an example of the data I'm working with

ID        DATE  
1         11/24/12 12:51 
1         11/24/12 12:52 
1         11/24/12 12:53
2         11/27/12 12:51
2         11/24/12 12:52
2         11/24/12 12:53  

What I need to do is generate an object that shows the earliest date/time for each value of ID like so:

ID        DATE  
1         11/24/12 12:51
2         11/27/12 12:51

I've tried several approaches but am still struggling.
Any suggestions would be appreciated!

Try this (as Roland suggests) using R base functions

DATE <- strptime(c("11/24/12 12:51", "11/24/12 12:52", "11/24/12 12:53", 
                   "11/27/12 12:51", "11/24/12 12:52", "11/24/12 12:53"),
                 "%m/%d/%y %H:%M")
ID <- rep(1:2, each=3)
DF <- data.frame(ID, DATE)

aggregate(DATE ~ ID, min, data=DF) 
  ID                DATE
1  1 2012-11-24 12:51:00
2  2 2012-11-24 12:52:00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM