r - 将值格式更改为 R 中的标准 30 秒格式
问题描述
我正在寻找将值格式数据的非标准更改(仅在Value
更改时读取)格式化为标准的 30 秒间隔格式。
我有什么df
::
Timestamp Value
6/26/2018 0:00:06 10
6/26/2018 0:01:06 15
6/26/2018 0:02:15 20
和dput
:
structure(list(Timestamp = c("6/26/2018 0:00:06", "6/26/2018 0:01:06",
"6/26/2018 0:02:15"), Value = c(10L, 15L, 20L)), .Names = c("Timestamp",
"Value"), class = "data.frame", row.names = c(NA, -3L))
我想要什么 formatted_df
:
Timestamp Value
6/26/2018 0:00:30 10
6/26/2018 0:01:00 10
6/26/2018 0:01:30 15
6/26/2018 0:02:00 15
6/26/2018 0:02:30 20
我的尝试:
使用 and 中的函数lubridate
,dplyr
我的间隔是 30 秒的倍数,但它没有标准化为 30 秒:
formatted <- df %>% mutate(Timestamp_Date = as.POSIXct(Timestamp, tz = "US/Eastern", usetz = TRUE, format="%m/%d/%Y %H:%M:%S"),
rounded_timestamp = ceiling_date(Timestamp_Date, unit = "30 seconds"))
与formatted
:
Timestamp Value Timestamp_Date rounded_timestamp
6/26/2018 0:00:06 10 6/26/2018 0:00:06 6/26/2018 0:00:30
6/26/2018 0:01:06 15 6/26/2018 0:01:06 6/26/2018 0:01:30
6/26/2018 0:02:15 20 6/26/2018 0:02:15 6/26/2018 0:02:30
我认为lubridate
并且dplyr
在这里会很有用,但我敢打赌data.table
可以做到。
解决方案
您可以使用data.table
滚动连接。
library(data.table)
#convert df into data.table and Timestamp into POSIX format
setDT(df)[, Timestamp := as.POSIXct(Timestamp, format="%m/%d/%Y %H:%M:%S")]
#create the intervals of 30seconds according to needs
tstmp <- seq(as.POSIXct("2018-06-26 00:00:30", tz=""),
as.POSIXct("2018-06-26 00:02:30", tz=""),
by="30 sec")
#rolling join between intervals and df
df[.(Timestamp=tstmp), on=.(Timestamp), roll=Inf]
输出:
Timestamp Value
1: 2018-06-26 00:00:30 10
2: 2018-06-26 00:01:00 10
3: 2018-06-26 00:01:30 15
4: 2018-06-26 00:02:00 15
5: 2018-06-26 00:02:30 20
有关更多信息,请阅读中的roll
论点?data.table
推荐阅读
- python-3.x - 如何使用 jaydebeapi 连接到 bigquery
- typescript - 当源类型具有不同原始类型的属性时,映射类型会产生错误
- r - Dplyr:将 2 变量汇总输出视为 2 x 2 矩阵
- c - 该分叉的进程树是什么?
- arrays - 如何在wordpress中编辑标题
- python - 类型错误:
() 接受 1 个位置参数,但在 simplefix get 方法中给出了 2 个 - sql - 评估移动由每个 ID 创建的最后 5 个订单
- angular - 以角度在多个选项卡之间共享会话存储
- jquery - jquery中的asp网格视图列单击事件
- java - 为什么堆转储的大小小于 JVM 消耗的大小?