R:如何获取时间序列数据中datetime列的最大值

时间:2015-04-16 21:44:23

标签: r datetime dataframe max time-series

我正在处理时间序列数据。我有2个日期时间列和1个会计周列。我给出了一个例子,我有一个像下面这样的情况,我需要得到EditDate的MAX。

EditDate <- c("2015-04-01 11:40:13", "2015-04-03 02:54:45","2015-04-07 11:40:13")
ID <- c("DL1X8", "DL1X8","DL1X8")
Avg <- c(38.1517, 38.1517, 38.1517)
Sig <- c(11.45880000, 11.45880000, 11.45880000)
InsertDate <- c("2015-04-03 9:40:00", "2015-04-03 9:40:00",2015-04-10 9:40:00)
FW <- c("39","39","40")

df1 <- data.frame(EditDate , ID, Avg, Sig, InsertDate, FW)

返回

+---------------------+-------+---------+-------------+--------------------+----+
|   EditDate          | ID    | Avg     |   Sig       |    InsertDate      | FW |
+---------------------+-------+---------+-------------+--------------------+----+
| 2015-04-01 11:40:13 | DL1X8 | 38.1517 | 11.45880000 | 2015-04-03 9:40:00 | 39 |
| 2015-04-03 02:54:45 | DL1X8 | 38.1517 | 11.45880000 | 2015-04-03 9:40:00 | 39 |
| 2015-04-07 11:40:13 | DL1X8 | 38.1517 | 11.45880000 | 2015-04-10 9:40:00 | 40 |
+---------------------+-------+---------+-------------+--------------------+----+

我想要的输出是

+---------------------+-------+---------+-------------+--------------------+----+
|   EditDate          | ID    | Avg     |   Sig       |    InsertDate      | FW |
+---------------------+-------+---------+-------------+--------------------+----+
| 2015-04-07 11:40:13 | DL1X8 | 38.1517 | 11.45880000 | 2015-04-10 9:40:00 | 40 |
+---------------------+-------+---------+-------------+--------------------+----+

我尝试使用sqldf使用库(RH2),但需要花费大量时间才能运行。

df2 <- sqldf("SELECT * FROM df1 
                        WHERE (EditDate = (SELECT MAX(EditDate) FROM df1))
                        ORDER BY EditDate ASC")

我不确定是否可以使用dplyr包完成。有人可以提供关于如何使用dplyr或任何其他替代方案来优化它的输入吗?

3 个答案:

答案 0 :(得分:4)

这是一个带有基础R

的衬里
df1[which.max(as.POSIXct(df1$InsertDate)), ]
#              EditDate    ID     Avg     Sig         InsertDate FW
# 3 2015-04-07 11:40:13 DL1X8 38.1517 11.4588 2015-04-10 9:40:00 40

data.table

library(data.table)
setDT(df1)[which.max(as.POSIXct(InsertDate))]
#               EditDate    ID     Avg     Sig         InsertDate FW
# 1: 2015-04-07 11:40:13 DL1X8 38.1517 11.4588 2015-04-10 9:40:00 40

答案 1 :(得分:3)

只需lubridate

library(lubridate)

df1[ymd_hms(EditDate)==max(ymd_hms(EditDate)), ]

df1[EditDate==as.character(max(ymd_hms(EditDate))), ]

答案 2 :(得分:1)

使用库data.tablelubridate如下:

 library(data.table)
 library(lubridate)
 setDT(df1)
 df1[,EditDate := ymd_hms(EditDate)]
 res <- df1[EditDate = max(EditDate)]