伙计们,你能不能帮助我制作数据的时间段?
我有以下数据集
Name Arrival Time
Ron 00:30
John 16:45
Sam 14:59
我想为每个到达时间包含时段,
Name Arrival Time Time Slot
Ron 00:30 00:00-01:00
John 16:45 16:00-17:00
Sam 14:59 14:00-15:00
如何在R中完成?
答案 0 :(得分:2)
这是一个策略:
arrival <- c('00:30','16:45','14:59')
a2 <- as.POSIXlt(arrival,'%H:%M',tz='')
paste(format(a2,'%H:00'),format(a2+3600,'%H:00'),sep='-')
[1] "00:00-01:00" "16:00-17:00" "14:00-15:00"
答案 1 :(得分:1)
另一种方法,我将时间视为完整的日期时间并将其保持为该格式:
arrivalString <- c("00:30", "16:45", "14:59")
arrival <- strptime(arrivalString, format = "%H:%M")
names <- c("Ron", "John", "Sam")
df <- data.frame(names, arrival)
slotbegin <- as.POSIXlt(df$arrival)
slotbegin$min <-rep(0, length(slotbegin))
df <- cbind(df, slotbegin)
slotend <- as.POSIXlt(df$arrival)
slotend$min <- rep(0, length(slotend))
slotend$hour <- slotend$hour + 1
df <- cbind(df, slotend)
输出:
names arrival slotbegin slotend
1 Ron 2013-10-09 00:30:00 2013-10-09 00:00:00 2013-10-09 01:00:00
2 John 2013-10-09 16:45:00 2013-10-09 16:00:00 2013-10-09 17:00:00
3 Sam 2013-10-09 14:59:00 2013-10-09 14:00:00 2013-10-09 15:00:00
答案 2 :(得分:0)
查看as.Date
和strftime
a <- "00:15"
astart <- paste(
strftime(
as.Date(
a,
"%H:%M"
),
"%H"
),
":00",
sep = ""
)
a <- "00:15"
aend <- paste(
as.integer(
strftime(
as.Date(
a,
"%H:%M"
),
"%H"
)
) + 1,
":00",
sep = ""
)
输出:
> astart
[1] "00:00"
> aend
[1] "1:00"