![](/img/trans.png)
[英]How to find the difference between two rows of data consisting of date and time in R
[英]Find rows with time between two values in R
我有一個數據幀臨時文件,如下所示:
Time Count Colour
01:02:30 11.000000 Red
17:05:49 52.000000 White
04:06:07 4.000000 Blue
01:07:03 30.000000 Red
20:08:30 4.000000 Yellow
時間最初是一個ISODate,我使用下面的代碼剝離它以獲得時間,這正是我想要的。
temp$Time = parse_iso_8601(temp$Time)
temp$Time <- as.POSIXlt(temp$Time)
library(chron)
temp$Time=times(format(temp$Time, format="%H:%M:%S"))
現在,我希望找到時間在02:00:00到05:00:00之間的行。 您能否建議如何做到這一點? 謝謝!
這是我的嘗試,
temp <- read.table(text = "Time Count Colour
01:02:30 11.000000 Red
17:05:49 52.000000 White
04:06:07 4.000000 Blue
01:07:03 30.000000 Red
20:08:30 4.000000 Yellow", header = TRUE)
library(chron)
temp$Time <- times(format(temp$Time, format="%H:%M:%S"))
temp[temp$Time >= 2/24 & temp$Time <= 5/24, ]
輸出:
> temp[temp$Time >= 2/24 & temp$Time <= 5/24, ]
Time Count Colour
3 04:06:07 4 Blue
下面的代碼顯示功能times
應映射[00:00:00,23:59:59.999 ...)到[0,1)
> as.numeric(times(paste(0:23, ":00:00", sep = "")))
[1] 0.00000000 0.04166667 0.08333333 0.12500000 0.16666667 0.20833333
[7] 0.25000000 0.29166667 0.33333333 0.37500000 0.41666667 0.45833333
[13] 0.50000000 0.54166667 0.58333333 0.62500000 0.66666667 0.70833333
[19] 0.75000000 0.79166667 0.83333333 0.87500000 0.91666667 0.95833333
因此,要確定Time
是否在02:00:00和05:00:00之間,可以檢查時間是否大於或等於2/24,小於或等於5/25。
不確定是否是您想要的。
假設temp
按日期和時間排序,如下所示
library(chron)
temp <- data.frame(
Record = 1:8,
Day = c(1, 1, 1, 1, 1, 2, 2, 2),
Time = c("01:02:30", "01:07:03", "04:06:07", "17:05:49", "20:08:30", "02:00:00", "02:15:00", "04:07:00")
)
temp$Time <- times(format(temp$Time, format="%H:%M:%S"))
> temp
Record Day Time
1 1 1 01:02:30
2 2 1 01:07:03
3 3 1 04:06:07
4 4 1 17:05:49
5 5 1 20:08:30
6 6 2 02:00:00
7 7 2 02:15:00
8 8 2 04:07:00
用R代碼來完成你的任務:
temp$Gap <- 24 * (c(NA, diff(temp$Time)) + c(NA, diff(temp$Day) > 0))
temp$Gap3hr <- temp$Gap >= 3 # 3 hour gap
temp$HourFromFirst <- 24 * (temp$Time - temp$Time[1]) + 24 * (temp$Day - temp$Day[1])
tempSelected <- lapply(which(temp$Gap3hr == TRUE), function(i) {
BeforeGap1hr <- (temp$HourFromFirst[i - 1] - temp$HourFromFirst) <= 1 & (temp$HourFromFirst[i - 1] - temp$HourFromFirst) >= 0
AfterGap1hr <- (temp$HourFromFirst - temp$HourFromFirst[i]) <= 1 & (temp$HourFromFirst - temp$HourFromFirst[i]) >= 0
temp[BeforeGap1hr | AfterGap1hr, ]
}
)
輸出:
> tempSelected
[[1]]
Record Day Time Gap Gap3hr HourFromFirst
3 3 1 04:06:07 2.984444 FALSE 3.060278
4 4 1 17:05:49 12.995000 TRUE 16.055278
[[2]]
Record Day Time Gap Gap3hr HourFromFirst
4 4 1 17:05:49 12.995000 TRUE 16.05528
5 5 1 20:08:30 3.044722 TRUE 19.10000
[[3]]
Record Day Time Gap Gap3hr HourFromFirst
5 5 1 20:08:30 3.044722 TRUE 19.10000
6 6 2 02:00:00 5.858333 TRUE 24.95833
7 7 2 02:15:00 0.250000 FALSE 25.20833
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.