Date formats (1)
As you saw earlier, R is picky about how it reads dates. To remind you, as.Date("09/28/2008") threw an error because it was not in the correct format. The fix for this is to specify the format you are using through the format argument:
as.Date("09/28/2008", format = "%m / %d / %Y")
[1] "2008-09-29"
This might look strange, but the basic idea is that you are defining a character vector telling R that your date is in the form of mm/dd/yyyy. It then knows how to extract the components and switch to yyyy-mm-dd.
There are a number of different formats you can specify, here are a few of them:
%Y: 4-digit year (1982)%y: 2-digit year (82)%m: 2-digit month (01)%d: 2-digit day of the month (13)%A: weekday (Wednesday)%a: abbreviated weekday (Wed)%B: month (January)%b: abbreviated month (Jan)
Cet exercice fait partie du cours
Intermediate R for Finance
Instructions
In this exercise you will work with the date, "1930-08-30", Warren Buffett's birth date!
- Use
as.Date()and an appropriate format to convert"08,30,1930"to a date (it is in the form of "month,day,year"). - Use
as.Date()and an appropriate format to convert"Aug 30,1930"to a date. - Use
as.Date()and an appropriate format to convert"30aug1930"to a date.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
# "08,30,30"
as.Date("08,30,1930", format = ___)
# "Aug 30,1930"
as.Date("Aug 30,1930", format = ___)
# "30aug1930"
as.Date("30aug1930", format = ___)