months() and weekdays() and quarters(), oh my!
As a final lesson on dates, there are a few functions that are useful for extracting date components. One of those is months()
.
my_date <- as.Date("2017-01-02")
months(my_date)
[1] "January"
Two other useful functions are weekdays()
to extract the day of the week that your date falls on, and quarters()
to determine which quarter of the year (Q1-Q4) that your date falls in.
This is a part of the course
“Intermediate R for Finance”
Exercise instructions
- A vector of
dates
has been created for you. - Extract the
months()
from these dates. - Extract the
quarters()
from these dates. - Another vector,
dates2
has also been created for you. - Use
weekdays()
to determine what day of the week the dates fell on, and assign them to the names ofdates2
usingnames()
. - Print
dates2
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# dates
dates <- as.Date(c("2017-01-02", "2017-05-03", "2017-08-04", "2017-10-17"))
# Extract the months
___
# Extract the quarters
___
# dates2
dates2 <- as.Date(c("2017-01-02", "2017-01-03", "2017-01-04", "2017-01-05"))
# Assign the weekdays() of dates2 as the names()
___
# Print dates2
___
This exercise is part of the course
Intermediate R for Finance
Learn about how dates work in R, and explore the world of if statements, loops, and functions using financial examples.
Welcome! Before we go deeper into the world of R, it will be nice to have an understanding of how dates and times are created. This chapter will teach you enough to begin working with dates, but only scratches the surface of what you can do with them.
Exercise 1: An introduction to dates in RExercise 2: What day is it?Exercise 3: From char to dateExercise 4: Many datesExercise 5: Date formats and extractor functionsExercise 6: Date formats (1)Exercise 7: Date formats (2)Exercise 8: Subtraction of datesExercise 9: months() and weekdays() and quarters(), oh my!What is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.