elmaroto10
elmaroto10

Reputation: 536

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

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

Upvotes: 2

Views: 411

Answers (1)

thelatemail
thelatemail

Reputation: 93813

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"

Upvotes: 2

Related Questions