Date to Day conversion R
You could use the format function with %a or %A
date <- as.Date("2017-05-20")
format(date, "%A")
[1] "Saturday"
format(date, "%a")
[1] "Sat"
If your original date is in the format "07/29/05" in the column A$Date you can call
strDays <- format(as.Date(A$Date, "%m/%d/%y"), "%A")
Find the day of a week
df = data.frame(date=c("2012-02-01", "2012-02-01", "2012-02-02"))
df$day <- weekdays(as.Date(df$date))
df
## date day
## 1 2012-02-01 Wednesday
## 2 2012-02-01 Wednesday
## 3 2012-02-02 Thursday
Edit: Just to show another way...
The wday
component of a POSIXlt
object is the numeric weekday (0-6 starting on Sunday).
as.POSIXlt(df$date)$wday
## [1] 3 3 4
which you could use to subset a character vector of weekday names
c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday")[as.POSIXlt(df$date)$wday + 1]
## [1] "Wednesday" "Wednesday" "Thursday"
Convert day of week number to weekday name in R
Simple way with dplyr.
library(dplyr)
df <- data.frame(day_number=0:6)
df$day_number <- recode(df$day_number,
"0"="Sunday",
"1"="Monday",
"2"="Tuesday",
"3"="Wednesday",
"4"="Thursday",
"5"="Friday",
"6"="Saturday")
Convert a date to a day number (monday = 1, tuesday = 2) in R
You can do this easily with lubridate
although it indexes Sunday as '1'. So since March 1, 2014 was a Saturday it would return '7'
library(lubridate)
wday(mdy("3-1-2014"))
[1] 7
Converting date with time in a column to week in character in R
We can floor the Date
object with floor_date
and then use format
library(dplyr)
library(lubridate)
df1 %>%
mutate(Time = as.POSIXct(Time),
favorite_time = format(floor_date(Time, "weeks",
week_start = 1), "%B %dth, %Y"))
# Case Time favorite_time
#1 1 2020-01-12 11:28:46 January 06th, 2020
#2 2 2020-01-22 10:17:24 January 20th, 2020
data
df1 <- structure(list(Case = 1:2, Time = c("2020-01-12 11:28:46",
"2020-01-22 10:17:24"
)), class = "data.frame", row.names = c(NA, -2L))
R function to take a date and output the day of the week for that date?
You can use the format
function:
format(as.Date("5/20/2020", '%m/%d/%Y'), "%a")
#[1] "Wed"
format(as.Date("5/20/2020", '%m/%d/%Y'), "%A")
[1] "Wednesday"
All the formats can be seen in the help page of strptime
.
Related Topics
Plotting a 95% Confidence Interval for a Lm Object
R:Convert Nested List into a One Level List
Passing by Reference a Data.Frame and Updating It with Rcpp
R Data.Table Join on Conditionals
How to Convert by the Minute Data to Hourly Average Data
Change Thickness Median Line Geom_Boxplot()
R: How to Select Files in Directory Which Satisfy Conditions Both on the Beginning and End of Name
Import Multiple Text Files in R and Assign Them Names from a Predetermined List
Aggregating Multiple Columns in Data.Table
Access Data.Table Columns with Strings
Keyboard Shortcut for Inserting Roxygen #' Comment Start
Fast Way of Getting Index of Match in List