Rebecca Neal
Rebecca Neal

Reputation: 11

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!

Upvotes: 0

Views: 893

Answers (1)

Jilber Urbina
Jilber Urbina

Reputation: 61154

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

Upvotes: 5

Related Questions