[英]Creating Time Intervals in R
我在R中有20,000個條目的數據集。 每個條目都有其發生的特定時間和日期。 我想創建每個6小時的時間間隔,即-6 AM-12 PM,12 PM-6 PM ...依此類推,並確保將數據相應地分類。 不需要日期,我只需要根據時間間隔對數據進行排序。
例如,如果某個條目的時間為12:35 PM,則將其分為12 PM-6 PM間隔。
歡迎所有想法。 S.
# create a dataframe with a column that represents a time
df <- data.frame(MyTimes = c("02:50:00","06:00:00", "11:10:30", "13:15:50", "17:00:00", "23:45:20"),
stringsAsFactors=FALSE)
# create a "time interval" column
df$Interval <- NA
df$Interval[df$MyTimes %between% c("00:00:00", "06:00:00")] <- "0 AM - 6 AM"
df$Interval[df$MyTimes %between% c("06:00:00", "12:00:00")] <- "6 AM - 12 PM"
df$Interval[df$MyTimes %between% c("12:00:00", "18:00:00")] <- "12 PM - 6 PM"
df$Interval[df$MyTimes %between% c("18:00:00", "24:00:00")] <- "6 PM - 0 AM"
df
# MyTimes Interval
# 1 02:50:00 0 AM - 6 AM
# 2 06:00:00 6 AM - 12 PM
# 3 11:10:30 6 AM - 12 PM
# 4 13:15:50 12 PM - 6 PM
# 5 17:00:00 12 PM - 6 PM
# 6 23:45:20 6 PM - 0 AM
一種更有效的方法是先轉換為秒,然后使用findInterval()
df$seconds <- period_to_seconds(hms(df$MyTimes))
myIntervals <- c("0 AM - 6 AM", "6 AM - 12 PM", "12 PM - 6 PM", "6 PM - 0 AM")
df$Interval<- myIntervals[findInterval(df$seconds, c(0, 6, 12, 18, 24) * 3600)]
# MyTimes Interval seconds
# 1 02:50:00 0 AM - 6 AM 10200
# 2 06:00:00 6 AM - 12 PM 21600
# 3 11:10:30 6 AM - 12 PM 40230
# 4 13:15:50 12 PM - 6 PM 47750
# 5 17:00:00 12 PM - 6 PM 61200
# 6 23:45:20 6 PM - 0 AM 85520
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.