What Time Is It On Mars?
That question can't be answered without asking more questions: Do you want the answer in relation to Mars time or Earth time? Since Mars has two moons, does it have twice as many months? Is a year 686 days or 365 days?
Calculating dates and times on earth are only slightly less complex. Data collected over a month's time might have 30 observations. Or 31. Or 28. Or 29. Even a consistent data series will yield inconsistent results if your calculations don't account for the variation in time. Programming Dates and Times in R is tricky business and a a complex programming challenge.
R Programming for Data Science: Dates and Times in R
LinkedIn Learning just released R Programming for Data Science: Dates and Times. It's part of a series of courses on R programming available by subscription or individual purchase. This course shows how to store, retrieve, format, compare, add, subtract, and extract dates and times using built-in R functions. It also covers specialized R packages such as lubridate, busdater, zoo, timelineR, anytime, datetime, and more.
An Example:
Base R has three data structures: Date, POSIXct, and POSIXlt. In the Dates and Times course, this is illustrated with the following code.
HAL_online <- as.Date("1992-01-12")
HAL_online now contains a Date structure, which is the number of days since January 1st, 1970. The Date structure doesn't account for times.
as.numeric(HAL_online) # which produces 8046
# 8046 is the number of days between 1970-01-01 and 1992-01-12
But...what if you define HAL_online as POSIXct?
HAL_online <- as.POSIXct("1992-01-12 11:23:34", tz = "America/Chicago")
as.integer(HAL_online)
# result is 695237014
POSIXct defines a date & time by the number of seconds since January 1, 1970. So now it's important to declare a time zone.
But wait - Base R has a third way to declare dates: POSIXlt.
HAL_online <- as.POSIXlt("1992-01-12 11:23:34", tz = "America/Chicago")
as.integer(HAL_online) # no longer an integer
# which produces ....
[1] 34 23 11 12 0 92 0 11 0 NA NA
Warning message:
NAs introduced by coercion
...which produces an odd set of numbers and a warning message. What is this?
That's because POSIXlt is a list of values. Unclass will reveal the structure...
> unclass(HAL_online) # this shows the components of the list
$sec
[1] 34
$min
[1] 23
$hour
[1] 11
$mday
[1] 12
$mon
[1] 0
$year
[1] 92
$wday
[1] 0
$yday
[1] 11
$isdst
[1] 0
$zone
[1] "CST"
$gmtoff
[1] NA
attr(,"tzone")
[1] "America/Chicago"
At this point, someone will bring up lubridate, a part of the tidyverse. Before you jump to that solution, you might want to know more about how it stores dates and times. You'll be pleased to know it's covered in the Date and Time course as well.
R Programming for Data Science: Dates and Times can be watched with your subscription, or purchased individually for $39.99
#linkedinlearning #rstats #r