r - Controlling how a date-time object is printed without coercing to a character? -
r - Controlling how a date-time object is printed without coercing to a character? -
imagine have info frame in columns represent dates or times. when working these columns, convenient have them formatted posixlt
objects (or other explicitly date/time oriented class).
however, when display these columns screen or print them out .csv, total iso8601 formatted time. realize can turn times character vector formatted want using format(col, format="%m-%y")
or whatever have in mind, i'm not keen on changing class of object print. other objects in r have print methods associated them, don't have explicitly coerce them. there way of date time classes of r objects i've overlooked?
edit:
here's minimal illustration of i'd hope achieve:
a.datetime = sys.time() a.datetime
displays:
2014-06-23 09:32:12
which format out in csv
write.csv(data.frame(a.datetime), "example.csv")
as describe above, realize can coerce character desired format manually, e.g.:
format(a.datetime, format="%y-%m") write.csv(data.frame(format(a.datetime, format="%y-%m")), "example.csv")
which not want have do; looking way object know how should printed without user having both apply formatting , coerce character vector shown above. (hopefully clarifies mean changing type, referring class of output, not class of argument).
i can seek define such class below, e.g. using s3 classes, still not print csv using format specified.
class(a.datetime) <- c("myclass", class(a.datetime)) attr(a.datetime, 'fmt') <- "%y-%m" print.myclass <- function(x) print(format(x, format=attr(x,"fmt"))) print.csv(data.frame(a.datetime), "temp.csv")
still prints csv total iso 8601 format.
some code expand on comment. r functional language operations on vector (and lists vectors) not alter vector, homecoming processed result , in case of datatime objects character vector. here's few views of posixlt object:
x <- as.posixlt("2000-01-01") x #[1] "2000-01-01 pst" x <- as.posixlt("2000-01-01 12:00:00") x #[1] "2000-01-01 12:00:00 pst" str(x) # posixlt[1:1], format: "2000-01-01 12:00:00" mode(x) #[1] "list" x[[1]] #[1] 0 x[[2]] #[1] 0 x[[3]] #[1] 12 x[[4]] #[1] 1 unlist(x) # sec min hr mday mon year wday yday isdst zone gmtoff # "0" "0" "12" "1" "0" "100" "6" "0" "0" "pst" na mode(x[[3]]) #[1] "numeric" # x[[10]]; mode(x[[10]]) #[1] "pst" #[1] "character"
notice unlist()
process converted list character vector. in r lists can have mixed modes single character element in posixlt
object end coercing of elements stored numeric values character elements. noted above posixlt object tricky utilize , dataframe functions not behave them because (well-behaved) dataframe columns atomic vectors rather lists.
r datetime datetime-format
Comments
Post a Comment