Search code examples
rfunctionclassdevelopment-environmentenvironment

Print environment using R


I'd like to write a function whose the output be an object of the class myclass with vector, list, integer an so on. Similarly to lmfunction. I tried to use an environment, but when I printed the function value the result is

#Term 1
> fit1
<environment: 0x00000000220d1998>
attr(,"class")
[1] "myclass"

However, when I print the lm function, the result is

> fit2
Call:
lm(formula = variable1 ~ variable2)

Coefficients:
     (Intercept)         variable2  
         49.0802            0.3603 

I know to access the individual values of the environment using $. But I'd like that the object was printed equal to lm function as showed.


Solution

  • Is that what you want?

    variable1 <- rnorm(10)
    variable2 <- rnorm(10)
    fit1 <- lm(variable1~variable2)
    fit2 <- fit1
    class(fit2) <- "myclass"
    
    # have a look at stats:::print.lm
    # and copy that function, hence define it as print method for your class or edit further:
    print.myclass <- function (x, digits = max(3L, getOption("digits") - 3L), ...) {
      cat("\nCall:\n", paste(deparse(x$call), sep = "\n", collapse = "\n"), 
          "\n\n", sep = "")
      if (length(coef(x))) {
        cat("Coefficients:\n")
        print.default(format(coef(x), digits = digits), print.gap = 2L, 
                      quote = FALSE)
      }
      else cat("No coefficients\n")
      cat("\n")
      invisible(x)
    }
    
    # now print
    print(fit2)
    
    # or
    fit2