Home > other >  Subsetting closure to print part of it with cat or print methods
Subsetting closure to print part of it with cat or print methods

Time:05-29

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..

# 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)

CodePudding user response:

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)

CodePudding user response:

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)

  •  Tags:  
  • r oop
  • Related