Home > Mobile >  How to find weekday number from datetime format in R
How to find weekday number from datetime format in R

Time:06-26

I have a dataset that contains DateTime in (dd-mm-yy hh: mm) format. I want to find the weekday number? I have tried the weekday function, but it is showing the wrong output.

wday("13-06-21 19:32")

6

CodePudding user response:

The datetime is not in the POSIXct class i.e. it is just character class. We need to convert and then apply

library(lubridate)
wday(dmy_hm("13-06-21 19:32"))
[1] 1

According to the ?wday

x- a POSIXct, POSIXlt, Date, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, or fts object.

Thus, a character input may return incorrect value

If we check the source code

> methods('wday')
[1] wday.default* wday.numeric*

> getAnywhere(wday.default)
function (x, label = FALSE, abbr = TRUE, week_start = getOption("lubridate.week.start", 
    7), locale = Sys.getlocale("LC_TIME")) 
{
    wday(as.POSIXlt(x, tz = tz(x))$wday   1, label, abbr, locale = locale, 
        week_start = week_start)
}

It is calling the as.POSIXlt on a incorrect format

> as.POSIXlt("13-06-21 19:32", tz = tz("13-06-21 19:32"))
[1] "0013-06-21 19:32:00 UTC"
> as.POSIXlt("13-06-21 19:32", tz = tz("13-06-21 19:32"))$wday 
[1] 5
> as.POSIXlt("13-06-21 19:32", tz = tz("13-06-21 19:32"))$wday   1
[1] 6

CodePudding user response:

You do not need extra packages such as lubridate.

Parse the date, convert to POSIXlt, and extract the weekday (and adjust for for its scale)

> D <- as.Date("13-06-21 19:32", "%d-%m-%y")
> D
[1] "2021-06-13"
> 
> as.POSIXlt(D)$wday   1    # see help(DateTimeClasses)
[1] 1
> 
  • Related