I'm currently working on a project in which I have a column called 'weekday'. This column contains day numbers 0:6. I'm new to R and want to create a new column that has weekday abbreviations for each number e.g. "0 = Sun, 1 = Mon", etc. Below is an image of my dataframe I am working with. Any help and tips would be much apppreciated.
CodePudding user response:
We can add your zero based weekday index to 2017-01-01
, which was a Sunday.
x <- c(0:6)
days_abbrev <- substr(weekdays(as.Date("2017-01-01") x), 1, 3)
days_abbrev
[1] "Sun" "Mon" "Tue" "Wed" "Thu" "Fri" "Sat"
Or using the excellent suggestion by @DarrenTsai we can pass TRUE
as the second parameter to weekdays()
to use abbreviations:
weekdays(as.Date("2017-01-01") x, TRUE)
CodePudding user response:
You can do this directly from the date column using %a
format...
format(as.Date("2017-01-05"), "%a")
[1] "Thu"