I have my dates formatted as 'YYYYMMDD' like '20150531' but now I want to separate my data into categories for the 7 days of the week by creating another variable called Day. How could I do this in R?
Asked
Active
Viewed 152 times
0
-
1From package `lubridate`: `wday(as_date("20201123"))` – DanY Nov 23 '20 at 21:51
-
Related https://stackoverflow.com/questions/9216138/find-the-day-of-a-week – Henry Nov 23 '20 at 21:52
-
@DanY Thank you very much! :) – Red Nov 24 '20 at 19:09
-
@Henry Thank you very much! :) – Red Nov 24 '20 at 19:09
2 Answers
0
We can convert to Date
class and then use format
to get the weekday name in base R
df1$Weekday <- format(as.Date(df1$date , '%Y%m%d'), '%a')
-output
df1
# date Weekday
#1 2015031 Sun
data
df1 <- data.frame(date = '2015031')

akrun
- 874,273
- 37
- 540
- 662
0
You can try weekdays()
function from base R
:
#Data
df <- data.frame(Date='2015031',stringsAsFactors = F)
df$Weekday <- weekdays(as.Date(df$Date,'%Y%m%d'))
Output:
df
Date Weekday
1 2015031 Sunday

Duck
- 39,058
- 13
- 42
- 84