Reputation: 7592
I'm trying to build my first ever R package. I started with a simple project that takes a date and "humanizes" it into the format "X [time unit] ago" (e.g., "3 days ago", "4 years ago" etc).
I wanted the result to have its own print method, so the value has a new class, and I defined a print.classname function.
When I run my new function and enter print(object)
is works as expected. But when I just enter object
, nothing shows. What might be causing this? Here's a shortened version of the function and the method:
humanize.now <- function(t) {
now<-Sys.time()
timediff<-diff(c(as.POSIXct(t), now))
answer<-as.numeric(timediff)
attributes(answer)<- list(unit=attributes(timediff)$units)
answer<-trunc(answer)
class(answer)<- "humanize"
return(answer)
}
print.humanize <- function(h) {
text<-paste0(h," ",attributes(h)$unit," ago")
text
}
(Update: edited the humanize.now function since my abbreviation of it introduced a mistake. Now the resulting object should be of class "humanize")
Upvotes: 2
Views: 234
Reputation: 9656
This is because your print.humanize()
function doesn't print the value. If you add a line that prints text
and returns it invisibly it should work:
print.humanize <- function(h) {
text <- paste0(h, " ", attributes(h)$unit, " ago")
print(text)
invisible(text)
}
Upvotes: 4