r 中仅时间(无日期)的顺序



我正在尝试制作一个仅包含一小时间隔的时间的序列,没有日期。它应该看起来像这样:

"00:00:00" "1:00:00" "2:00:00" "3:00:00"

我知道这段代码有效:

dat <- seq(
  from=as.POSIXct("00:00:00","%H:%M:%S", tz="UTC"),
  to=as.POSIXct("23:00:00", "%H:%M:%S", tz="UTC"),
  by="hour"
)

这给了

[1] "2018-04-10 00:00:00 UTC" "2018-04-10 01:00:00 UTC" "2018-04-10 02:00:00 UTC" "2018-04-10 03:00:00 UTC" "2018-04-10 04:00:00 UTC"
 [6] "2018-04-10 05:00:00 UTC" "2018-04-10 06:00:00 UTC" "2018-04-10 07:00:00 UTC" "2018-04-10 08:00:00 UTC" "2018-04-10 09:00:00 UTC"
[11] "2018-04-10 10:00:00 UTC" "2018-04-10 11:00:00 UTC" "2018-04-10 12:00:00 UTC" "2018-04-10 13:00:00 UTC" "2018-04-10 14:00:00 UTC"
[16] "2018-04-10 15:00:00 UTC" "2018-04-10 16:00:00 UTC" "2018-04-10 17:00:00 UTC" "2018-04-10 18:00:00 UTC" "2018-04-10 19:00:00 UTC"
[21] "2018-04-10 20:00:00 UTC" "2018-04-10 21:00:00 UTC" "2018-04-10 22:00:00 UTC" "2018-04-10 23:00:00 UTC"

但这不是我想要的。因此我尝试了

library(chron)
seq(from = times("00:00:00"), to =times("23:00:00"), by="hour")

这给出了一个错误

Error in convert.times(times., fmt) : format h:m:s may be incorrect
In addition: Warning message:
In unpaste(times, sep = fmt$sep, fnames = fmt$periods, nfields = 3) :
  wrong number of fields in entry(ies) 1

我现在被困住了,所以我希望有人可以帮助我解决这个问题。当然,我可以把它打出来,但我想有一个干净的解决方案。

使用提供times类的包 chron:

library(chron)
times("00:00:00") + (0:23)/24
#[1] 00:00:00 01:00:00 02:00:00 03:00:00 04:00:00 05:00:00 06:00:00 07:00:00 08:00:00 09:00:00 10:00:00 11:00:00 12:00:00 13:00:00 14:00:00
#[16] 15:00:00 16:00:00 17:00:00 18:00:00 19:00:00 20:00:00 21:00:00 22:00:00 23:00:00
您可以使用

strftime()将任何格式的值提取为字符:

dat <- seq(
  from=as.POSIXct("00:00:00","%H:%M:%S", tz="UTC"),
  to=as.POSIXct("23:00:00", "%H:%M:%S", tz="UTC"),
  by="hour"
)
strftime(dat, format="%H:%M:%S")
#"02:00:00" "03:00:00" "04:00:00" "05:00:00" "06:00:00" "07:00:00"
#"08:00:00" "09:00:00" "10:00:00" "11:00:00" "12:00:00" "13:00:00"
#"14:00:00" "15:00:00" "16:00:00" "17:00:00" "18:00:00" "19:00:00" 
#"20:00:00" "21:00:00" "22:00:00" "23:00:00" "00:00:00" "01:00:00"

当你有一个POSIXct类时,要仅提取小时,分钟和秒,您只需要执行以下操作:

as.character(format(from, "%H:%M:%S"))
as.character(format(to, "%H:%M:%S"))

最新更新