Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract weekdays from a set of dates in R

Tags:

r

lubridate

I know using the lubridate package, I can generate the respective weekday for each date of entry. I am now dealing with a large dataset having a lot of date entries and I wish to extract weekdays for each date entries. I think it is quite impossible to search for each date and to find weekdays. I will love to have a function that will allow me to insert my date column from my data frame and will produce days corresponding to each dates of the frame.

my frame is like

uinq_id Product_ID Date_of_order count
1 Aarkios04_2014-09-09  Aarkios04    2014-09-09    10
2    ABEE01_2014-08-18     ABEE01    2014-08-18     1
3    ABEE01_2014-08-19     ABEE01    2014-08-19     0
4    ABEE01_2014-08-20     ABEE01    2014-08-20     0
5    ABEE01_2014-08-21     ABEE01    2014-08-21     0
6    ABEE01_2014-08-22     ABEE01    2014-08-22     0

i am trying to generate

uinq_id Product_ID Date_of_order count                      weekday   
1 Aarkios04_2014-09-09  Aarkios04    2014-09-09    10       Tues
2    ABEE01_2014-08-18     ABEE01    2014-08-18     1       Mon  
3    ABEE01_2014-08-19     ABEE01    2014-08-19     0       Tues   
4    ABEE01_2014-08-20     ABEE01    2014-08-20     0       Wed 
5    ABEE01_2014-08-21     ABEE01    2014-08-21     0       Thurs
6    ABEE01_2014-08-22     ABEE01    2014-08-22     0       Fri

any help will be highly beneficial. thank you.

like image 365
Hindol Ganguly Avatar asked May 31 '16 11:05

Hindol Ganguly


3 Answers

Using weekdays from base R you can do this for a vector all at once:

temp = data.frame(timestamp = Sys.Date() + 1:20)
> head(temp)
   timestamp
1 2016-06-01
2 2016-06-02
3 2016-06-03
4 2016-06-04
5 2016-06-05
6 2016-06-06
temp$weekday = weekdays(temp$timestamp)
> head(temp)
   timestamp   weekday
1 2016-06-01 Wednesday
2 2016-06-02  Thursday
3 2016-06-03    Friday
4 2016-06-04  Saturday
5 2016-06-05    Sunday
6 2016-06-06    Monday
like image 110
Paul Hiemstra Avatar answered Oct 12 '22 02:10

Paul Hiemstra


We can use format to get the output

df1$weekday <- format(as.Date(df1$Date_of_order), "%a")
df1$weekday
#[1] "Tue" "Mon" "Tue" "Wed" "Thu" "Fri"

According to ?strptime

%a - Abbreviated weekday name in the current locale on this platform. (Also matches full name on input: in some locales there are no abbreviations of names.)

like image 45
akrun Avatar answered Oct 12 '22 02:10

akrun


library(lubridate)

date <- as.Date(yourdata$Date_of_order, format = "%Y/%m/%d")
   
yourdata$WeekDay <- weekdays(date)
             
like image 43
Anya Sti Avatar answered Oct 12 '22 03:10

Anya Sti