# # A function to convert from character to mcdDate # Called by UseMethod() as.mcdDate.character <- function(from) { value <- as.POSIXct(from, tz="GMT", format="%Y%m%d%H%M%OS") class(value) = c("mcdDate", class(value)) value } # UseMethod gets the class of from, appends it to "as.mcdDate" and # if that exists, call it. If the class is a list, it will try each # in turn until one works or errors if none work. Character is all I have defined. as.mcdDate <- function(from) { UseMethod("as.mcdDate") }a <- as.mcdDate("20131010123456.789") str(a)
mcdDate[1:1], format: "2013-10-10 12:34:56"
class(a)
[1] "mcdDate" "POSIXct" "POSIXt"
# since we don't have a method as.mcdDate.double() or as.mcdDate.numeric(), # this will fail as.mcdDate(123)
Error: no applicable method for 'as.mcdDate' applied to an object of class "c('double', 'numeric')"
# ###################################################################################### # Try just faking it # NOTE: This is not something that you would likely want to do in a real program # Just for instructive use. :) # # It doesn't look like we have to really create an object, we can just assign # the class names and attributes (for simple classes anyway). POSIXct is a simple # class that holds one double, and has a tzone attribute. so... # # First this is what we want to duplicate a <- as.POSIXct(123, tz="GMT", origin="1970-1-1") a
[1] "1970-01-01 00:02:03 GMT"
class(a)
[1] "POSIXct" "POSIXt"
attributes(a)
$tzone [1] "GMT" $class [1] "POSIXct" "POSIXt"
b <- 123 class(b)
[1] "numeric"
class(b) <- c("POSIXct","POSIXt") b
[1] "1969-12-31 17:02:03 MST"
attr(b,"tzone") <- "GMT" b
[1] "1970-01-01 00:02:03 GMT"
str(b)
POSIXct[1:1], format: "1970-01-01 00:02:03"
# And it works on arrays too b = c(1:10) class(b) <- c("POSIXct","POSIXt") attr(b,"tzone") <- "GMT" b
[1] "1970-01-01 00:00:01 GMT" "1970-01-01 00:00:02 GMT" [3] "1970-01-01 00:00:03 GMT" "1970-01-01 00:00:04 GMT" [5] "1970-01-01 00:00:05 GMT" "1970-01-01 00:00:06 GMT" [7] "1970-01-01 00:00:07 GMT" "1970-01-01 00:00:08 GMT" [9] "1970-01-01 00:00:09 GMT" "1970-01-01 00:00:10 GMT"
str(b)
POSIXct[1:10], format: "1970-01-01 00:00:01" "1970-01-01 00:00:02" ...