Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

function (x, y) 1+5*exp(-x^2 - y^2) <environment: 0x0000020dd971cd10>

I can’t turn this closure to a string or subset it to extract only surface formula 1+5*exp(-x^2 - y^2)
Help please..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# object template
chrt <- function(domain, n, f, col, ...) {
  x <- y <- seq(min(domain), max(domain), length.out = n)
  fun <- function(x, y) {}
  body(fun) <- substitute(f)
  structure(list(x = x, 
                 y = y, f = fun, col=col, ...), 
            class = "mychr")
}

# print method
print.mychr <- function(object) {
  `%G%` <- paste0
  cat("\nObject has class: " %G% class(object) %G% 
        ", color: " %G% as.character(object$col) %G% "\n\n")
  print(object$f)
}
# object call
chr1 <- chrt(c(-6, 6), 
             n = 30, 
             1+5*exp(-x^2 - y^2),
             col = 'blue')
print(chr1)

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading