gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:49:50 25 4
gpt4 key购买 nike

我正在处理时间序列数据。我有 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 |
+---------------------+-------+---------+-------------+--------------------+----+

我尝试使用库(RH2)使用 sqldf,但运行需要很多时间。
df2 <- sqldf("SELECT * FROM df1 
WHERE (EditDate = (SELECT MAX(EditDate) FROM df1))
ORDER BY EditDate ASC")

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

最佳答案

这是一个带有基础 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

关于R:如何获取时间序列数据中日期时间列的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29686522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com