r - 以毫秒为单位计算时间差
问题描述
我想以毫秒为单位逐行计算时间戳的差异。下面示例中的差异(time_diff)应始终为 0.2,但我也得到高于和低于 0.2 的值。
当将毫秒除以秒和/或向对象添加numeric
值时,问题就开始了POSIXct
。
我认为这是一些浮点问题,所以我尝试指定digits.sec 和数字的数量、舍入、截断等......但问题仍然存在。
为什么会这样以及如何解决这个问题?
library(dplyr)
options("digits.secs"=10)
options(digits = 10)
id <- 1:12
time <- c("9:34:50" , "9:34:50" , "9:34:51" , "9:34:51" , "9:34:51" , "9:34:51" ,
"9:34:51" , "9:34:52" , "9:34:52" , "9:34:52" , "9:34:52" , "9:34:52")
ms <- c(600,800,0,200,400,600,800,0,200,400,600,800)
time <- as.POSIXct(time, format="%H:%M:%S", tz="GMT")
# Problem begins here
timeNew <- time + (ms/1000)
timeNewDf <- data.frame(id=id,
time=timeNew)
timeNewDf %>% dplyr::mutate(
time_diff = c(diff(time),0)) %>%
dplyr::rowwise()
解决方案
POSIXct 将比精确时间更接近于其最近的浮点数。添加偏移量以适应浮点近似并显示到毫秒的 1 位数。
library(dplyr)
options("digits.secs"=1) # showing upto 1 digit
# test data
id <- 1:12
time <- c("9:34:50" , "9:34:50" , "9:34:51" , "9:34:51" , "9:34:51" ,
"9:34:51" , "9:34:51" , "9:34:52" , "9:34:52" , "9:34:52" , "9:34:52" , "9:34:52")
ms <- c(600,800,0,200,400,600,800,0,200,400,600,800)
time <- as.POSIXct(time, format="%H:%M:%S", tz="GMT")
# offset to cater to floating point approximations
timeNew <- time + (ms/1000) + .0001
timeNewDf <- data.frame(id=id, time=timeNew)
timeNewDf %>% mutate(time_diff = round(c(diff(time),0),1)) # rounding to 1 decimal digit
#1 1 2018-05-30 09:34:50.6 0.2 secs
#2 2 2018-05-30 09:34:50.8 0.2 secs
#3 3 2018-05-30 09:34:51.0 0.2 secs
#4 4 2018-05-30 09:34:51.2 0.2 secs
#5 5 2018-05-30 09:34:51.4 0.2 secs
#6 6 2018-05-30 09:34:51.6 0.2 secs
#7 7 2018-05-30 09:34:51.8 0.2 secs
#8 8 2018-05-30 09:34:52.0 0.2 secs
#9 9 2018-05-30 09:34:52.2 0.2 secs
#10 10 2018-05-30 09:34:52.4 0.2 secs
#11 11 2018-05-30 09:34:52.6 0.2 secs
#12 12 2018-05-30 09:34:52.8 0.0 secs
推荐阅读
- google-visualization - 谷歌可视化 - 选择处理程序不起作用
- report - 在 AdSense v2 中接收报告数据
- gradle - Gradle 守护进程类加载器
- php - 如何在我的页面上显示我教父的名字
- java - 将 MutableList 或 ArrayList 从 Activity A 传递和检索到 B
- python - AttributeError: set_model Error (Keras callbacks)
- arrays - 在 hive 中将字符串数组转换为 int 数组时保留顺序
- reactjs - 如何从material-ui返回值状态
使用 inputProps - powershell - PowerShell - 对存储在本地设备中的 Chrome 91.0.4472.106 cookie 应用 AES-256-GCM 解密
- python - 计算熊猫数据框中 ID 的出现次数