代码之家  ›  专栏  ›  技术社区  ›  Wagner Jorge

使用R的打印环境

  •  -2
  • Wagner Jorge  · 技术社区  · 6 年前

    我想写一个函数,它的输出是类的对象 myclass lm 作用我试着用一个 environment

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

    但是,当我打印 lm 函数,结果是

    > fit2
    Call:
    lm(formula = variable1 ~ variable2)
    
    Coefficients:
         (Intercept)         variable2  
             49.0802            0.3603 
    

    我知道如何访问 使用 $ . 但我希望打印的对象与 lm 功能如图所示。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Tino    6 年前

    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