Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find weekday number from datetime format in R

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading