用户 类 的打印方法

Print method with user classes

我正在试验 S3-class 方法和通用函数,但我遇到了一个问题,我认为这突出了我的想法中的误解。也许我对打印的工作方式或内部存储 valuesattributes 的工作方式感到困惑?

我试过 google 无济于事,可能是因为我不太确定自己在找什么。

设置

library(data.table)

# trivial data
dt <- CJ(letter = c("A", "B", "C"), number = 1:4)

# -- generic functions
coverage <- function (x, ...) {
  UseMethod("coverage", x)
}

prettyprint <- function (x, ...) {
  UseMethod("prettyprint", x)
}

Class 方法

# coverage method to find % of data.table satisfying an expr
coverage.data.table <- function(dt, subset, desc) {
  e <- parse(text = subset)  # parse condition to expression
  coverage <- dt[eval(e), .N]/dt[, .N]  # express coverage as a percent 
  class(coverage) <- c("coverage", class(coverage))  # set as 'coverage' class
  attributes(coverage)[["desc"]] <- desc  # carry description for printing
  coverage
}

# human readable data.table coverage
prettyprint.coverage <- function(coverage) {
  desc <- attributes(coverage)[["desc"]]
  paste0(round(coverage*100, 2), "% ", desc)
}

# normal printing
print.coverage <- function(coverage) {

  # unsure what to put in here such that I can use
  # this value with standard other operations such 
  # as multiplication

}

coverageB <- coverage(dt, "letter == \"B\"", "of data.table is in B")

> coverageB  # prints nothing as expected from empty function
> prettyprint(coverageB)
  [1] "33.33% of data.table is in B"

打印 coverageB 不加载 print.coverage 给出

> coverageB
[1] 0.3333333
attr(,"class")
[1] "coverage" "numeric" 
attr(,"desc")
[1] "of data.table is in B"

我想要一些方法来仅打印 0.3333333

非常感谢您的帮助。谢谢。

(作为旁注,我确信 eval(parse(...)) 语句不是正确的做事方式。任何指示也将不胜感激。)

我也不确定该用什么标题 - 如果有人有任何更合适的建议,我很乐意更改它。

这里有两种更好的可能性,第一种采用您的方法(由于自动索引可能会更快,但我没有进行基准测试):

coverage.data.table <- function(dt, subset, desc) {
  coverage <- dt[eval(substitute(subset)), .N]/dt[, .N]  # express coverage as a percent 
  #coverage <- dt[, mean(eval(substitute(subset)))]  # express coverage as a percent 
  class(coverage) <- c("coverage", class(coverage))  # set as 'coverage' class
  attributes(coverage)[["desc"]] <- desc  # carry description for printing
  coverage
}

然后你这样称呼它:

coverageB <- coverage(dt, letter == "B", "of data.table is in B")

这里有一个 print 方法,它使用 c 删除所有属性(参见其文档):

# normal printing
print.coverage <- function(coverage) {
  print.default(c(coverage))
} 

coverageB
#[1] 0.3333333
prettyprint(coverageB)
#[1] "33.33% of data.table is in B"

但是,我不明白您对 print 方法的评论。 print 方法与乘法没有任何关系。