在 R 中使用自己的方法创建新 class 时,为什么仅输入对象名称时不自动打印?
When creating new class with its own method in R, why doesn't it autoprint when entering just the object name?
我正在尝试构建我的第一个 R 包。我从一个简单的项目开始,该项目需要一个日期并将其 "humanizes" 转换为 "X [time unit] ago" 格式(例如,“3 天前”、“4 年前”等)。
我希望结果有自己的打印方法,所以值有一个新的 class,我定义了一个 print.classname 函数。
当我 运行 我的新功能并输入 print(object)
时,它按预期工作。但是当我输入 object
时,没有任何显示。这可能是什么原因造成的?这是函数和方法的简化版本:
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
}
(更新:编辑了 humanize.now 函数,因为我的缩写引入了一个错误。现在生成的对象应该是 class "humanize")
这是因为您的 print.humanize()
函数没有打印值。如果你添加一行打印 text
和 returns 它应该无形地工作:
print.humanize <- function(h) {
text <- paste0(h, " ", attributes(h)$unit, " ago")
print(text)
invisible(text)
}
我正在尝试构建我的第一个 R 包。我从一个简单的项目开始,该项目需要一个日期并将其 "humanizes" 转换为 "X [time unit] ago" 格式(例如,“3 天前”、“4 年前”等)。
我希望结果有自己的打印方法,所以值有一个新的 class,我定义了一个 print.classname 函数。
当我 运行 我的新功能并输入 print(object)
时,它按预期工作。但是当我输入 object
时,没有任何显示。这可能是什么原因造成的?这是函数和方法的简化版本:
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
}
(更新:编辑了 humanize.now 函数,因为我的缩写引入了一个错误。现在生成的对象应该是 class "humanize")
这是因为您的 print.humanize()
函数没有打印值。如果你添加一行打印 text
和 returns 它应该无形地工作:
print.humanize <- function(h) {
text <- paste0(h, " ", attributes(h)$unit, " ago")
print(text)
invisible(text)
}