Subsetting closure to print part of it with cat or print methods

Viewed 43

I'd like to create a print method, printing object class, color and 3d surface formula. However in the object call, this surface formula needs to be as it is now, that's why body and substitute were used. So my method correctly prints class and color, but for surface formula cat doesn't work and print gives the following output which is a closure

2 Answers

Use as.list and print third element which is the formula.

print.mychr <- function(object) {
  `%G%` <- paste0
  cat("\nObject has class: " %G% class(object) %G% 
        ", color: " %G% as.character(object$col) %G% "\n\n")
  print(as.list(object$f)[[3]])
}

print(chr1)
# Object has class: mychr, color: blue
# 
# 1 + 5 * exp(-x^2 - y^2)

You can deparse the body of f to convert it to character:

print.mychr <- function(object) {
  `%G%` <- paste0
  cat("\nObject has class: ", class(object),
        ", color: ", as.character(object$col),
        ", formula: ", deparse(body(object$f)))
}

# object call
chr1 <- chrt(c(-6, 6), 
             n = 30, 
             1+5*exp(-x^2 - y^2),
             col = 'blue')
print(chr1)
#> 
#> Object has class:  mychr , color:  blue , formula:  1 + 5 * exp(-x^2 - y^2)

Created on 2022-05-28 by the reprex package (v2.0.1)

Related