The
as.date()
function creates objects of the class “Date
“, via input of character representations of dates.
Answers to the exercises are available here.
Exercise 1
The format of as.Date(x, ...)
accepts character dates in the format, “YYYY-MM-DD”.
For the first exercise, use the c()
function, and as.date()
, to convert “2010-05-01
” and “2004-03-15
” to class “date
” objects. Set a variable called, “Exer1Dates
“.
Exercise 2
With as.Date(x, format, ...)
, the structure of the character dates are specified by the “format =
” parameter.
For this exercise, use as.date(x, format, ...)
to convert “07/19/98
” to a date object within the variable, “Exer2Date
“.
Exercise 3
The parameter, “origin =
” converts dates from Windows Excel, (where 1900 is mistakenly designated as a leap year), to R format, via “origin = "1899-12-30"
“.
Therefore, convert the Windows Excel dates of “31539
“, “31540
“, and
“31541
” to date objects, without setting a variable.
Exercise 4
Convert “02/07/10
“, “02/23/10
“, “02/08/10
“, “02/14/10
“, and
“02/10/10
“, into date objects within the variable, “Exer4Dates
“.
Exercise 5
Find the mean of the date object variable “Exer4Dates
“.
Exercise 6
Find the max date in “Exer4Dates
“.
Exercise 7
Convert “10/25/2005
“, and “06/08/1971
” into a date object.
Exercise 8
Convert “Exer4Dates
” to character data. Set a variable called, “chrDates
“.
Exercise 9
Use the “format()
“, and “Sys.Date()
“, functions to print today’s date, with a format of “%B %d %Y
“.
Exercise 10
Use “format()
” and “Sys.time()
” to print today’s date, with the time zone set to “Hawaii Standard Time
“.
Image by Maklay62 (Pixabay post) [CC0 Public Domain ], via Pixabay.
I found that Exercise 3 only worked by adding a format argument as follows:
as.Date(c(‘31539’, ‘31540’, ‘31541’), origin=’1899-12-30′, format=’%d’)
Without it, the response was:
Error in charToDate(x) :
character string is not in a standard unambiguous format
You are quoting the numbers like ‘31539’, which will convert them to a character. Notice that the linked answers don’t have quotes around the numbers.
Ah, subtle. Thanks.