[英]Loop to measure difference in time between two values
Im trying to calculate the occupancy rate in rooms per hour, I want to do this by checking how many minutes in an hour a room is occupied.我试图计算每小时房间的入住率,我想通过检查一个房间一小时内被占用多少分钟来做到这一点。 Occupancy time is when column 'occupied' is 1 and change to 0. I have succeeded in calculating the occupancy minutes by using:
占用时间是当列“占用”为 1 并更改为 0 时。我已成功使用以下方法计算占用分钟数:
Timediff <- Test %>% arrange(Date_Time)%>% mutate(difftime= difftime(lead(Date_Time),Date_Time, units = "mins"))
And my table looks like this now:我的桌子现在看起来像这样:
So what I have in mind is this: To calculate the occupancy rate per hour, I'm adding all the occupied time (difftime for every 'occupied = 1') in that hour, divide it by 60, times 100%.所以我想到的是:为了计算每小时的占用率,我将在那一小时内的所有占用时间(每个“占用 = 1”的差异时间)相加,除以 60,乘以 100%。
Example:例子:
July 30th 2017: 2017 年 7 月 30 日:
Occupancy rate from 11.00 till 12.00 (11.59) = (14+1)/60*100% 11.00 至 12.00 入住率 (11.59) = (14+1)/60*100%
12.00 till 13.00 (12.59) = (14+5)/60*100% 12:00 到 13:00 (12.59) = (14+5)/60*100%
13.00 till 14.00 (13.59) = (11+14)/60*100% 13:00 到 14:00 (13.59) = (11+14)/60*100%
Etc. etc.等等等等。
How can I do this?我怎样才能做到这一点?
Considering that your picture represents one "room" then, you just want to use diff(yourdata$Date_Time)
and you will have a vector of occupiedtime;考虑到您的图片代表一个“房间”,您只想使用
diff(yourdata$Date_Time)
并且您将拥有一个占用时间的向量; not occupiedtime;不占用时间; etc.
等等
You can use the lag function instead of a loop.您可以使用滞后 function 而不是循环。
library(dplyr)
df = df %>%
mutate(Date_Time_diff = difftime(Date_Time, lag(Date_Time), units = 'mins'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.