r - 将 HH:MM:SS 列转换为 ZT 时间
问题描述
我希望有人可以帮助我解决 R-studio 中的逻辑问题。我有一个相当大的数据集,其中“时间”是我的专栏之一。此列的值从 00:00:00 到 23:59:00,格式为 HH:MM:SS。
由于我在分析这种格式的时间时遇到了一些麻烦,我正在尝试创建一个名为“ZT”的新列,在其中我将这个时间列转换为 ZT 时间。灯在早上 7 点亮,所以需要时间 07:00:00 对应 ZT=0,07:01:00 对应 ZT=0.016……以此类推。
有人可以帮我吗?将不胜感激!
解决方案
不确定这是否是您想要的,但这似乎可以将格式为 HH:MM:SS 的时间字符向量转换为格式为 HH:MM:SS 从早上 7 点开始为 00 的 ZT 时间: 00:00。
当您声明 07:01:00 应对应于 ZT=0.016 时,我不清楚您的确切含义,但也许这可以作为一个开始。
公平警告这有点慢(在我的机器上花了大约 1 分钟)但也许其他人可以帮助对其进行矢量化并加快速度:
#Make Some Fake Data
df<-data.frame(Time=format(seq(ISOdate(2020,1,1), ISOdate(2020,2,1), by = "min"), '%H:%M:00'), Variable1=runif(n=44641))
#We need the help of a an external package to handle time in HH:MM:SS format
library(lubridate)
time_store<- hms(df$Time) #Convert your times to HMS format
ZT_vec<-vector() #Create an empty vector that we will fill in
for (i in 1:length(time_store)){ #iterate over each observation
if (hour(time_store[i])<7){ #Make sure the conversions are going the right direction
ZT<-time_store[i]+hours(17)
ZT_vec<-c(ZT_vec,sprintf("%02d:%02d:%02d", hour(ZT), minute(ZT), second(ZT))) #format the times in HH:MM:SS
} else {
ZT<-time_store[i]-hours(7)
ZT_vec<-c(ZT_vec,sprintf("%02d:%02d:%02d", hour(ZT), minute(ZT), second(ZT)))
}
}
df<-cbind(df,ZT_vec) #Bind on our new column
head(df)
Time Variable1 ZT_vec
12:00:00 0.6560604 05:00:00
12:01:00 0.3485023 05:01:00
12:02:00 0.8396784 05:02:00
12:03:00 0.4773929 05:03:00
12:04:00 0.6969242 05:04:00
12:05:00 0.5371502 05:05:00
head(df[4020:4025,])
Time Variable1 ZT_vec
06:59:00 0.6758364 23:59:00
07:00:00 0.1255861 00:00:00
07:01:00 0.2789485 00:01:00
07:02:00 0.2175933 00:02:00
07:03:00 0.1855100 00:03:00
07:04:00 0.1632865 00:04:00
推荐阅读
- reactjs - 反应,链接中道具“组件”的值无效
- c++ - 有没有办法让编译器在我放置字符串而不是 nlohmann::json 对象时抛出错误?
- swift - 允许用户在 macCatalyst 中自定义 Touch Bar
- delphi - 屏幕调整大小delphi后如何在运行时处理组件的重新对齐
- ruby-on-rails - 使用 capybara 设计登录验收测试
- arrays - Translate Array with Array
- selenium-webdriver - How to handle elements with type = "hidden" in Serenity BDD?
- python - Unable to query postgress sql from python
- ios - 如何在 Swift 中更改 UIView 中所有标签的颜色?
- azure-devops - azure pipeline TFVC check if a specific Build pipeline artifacts exist for a specific Branch name and specific tag