在R中为另一个变量的每个值查找变量的最小值

时间:2021-07-11 18:51:55

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

我对R很新,我正试图找到每个ID号码的最小日期/时间。以下是我正在使用的数据示例

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值的最早日期/时间,如下所示:

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!

我尝试了几种方法,但仍在努力。任何建议,将不胜感激!

1 个解决方案

#1


5  

Try this (as Roland suggests) using R base functions

试试这个(正如Roland建议的那样)使用R基函数

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

#1


5  

Try this (as Roland suggests) using R base functions

试试这个(正如Roland建议的那样)使用R基函数

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