How to create day part in R from a vector of POSIXct timestamps?

痴心易碎 提交于 2019-12-11 12:41:55

问题


I have a long series of POSIXct timestamps. I would like to return, for each record a day part, including day of the week. For example:

[1] Sunday night
[2] Sunday night
[3] Sunday afternoon
[4] Saturday night
[5] Sunday afternoon

... and so on.

Below is a small sample of the data:

my_dates <- as.POSIXct(c("2000-03-12 19:40:00 AEDT",
                            "2000-03-19 17:40:00 AEDT", 
                            "2000-03-26 14:10:00 AEST", 
                            "2000-04-01 19:40:00 AEST", 
                            "2000-04-09 14:10:00 AEST",
                            "2000-04-16 14:40:00 AEST",
                            "2000-04-22 19:40:00 AEST",
                            "2000-04-30 14:10:00 AEST",
                            "2000-05-07 14:10:00 AEST",
                            "2000-05-14 14:10:00 AEST"))

I have tried a lot of different things, but I always end up losing the date format.

Any help would be much appreciated. Thanks


回答1:


Some creative formatting and cutting should be able to get you there:

paste(
  format(my_dates, "%A"),
  c("night","morn","afternoon","night")[
    cut(as.numeric(format(my_dates,"%H")), c(0,5,11,17,23))
  ]
)
# [1] "Sunday night"     "Sunday afternoon" "Sunday afternoon" "Saturday night"  
# [5] "Sunday afternoon" "Sunday afternoon" "Saturday night"   "Sunday afternoon"
# [9] "Sunday afternoon" "Sunday afternoon"


来源:https://stackoverflow.com/questions/36464848/how-to-create-day-part-in-r-from-a-vector-of-posixct-timestamps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!