创造漂亮的输出

hej*_*seb 3 r function output

我一直致力于一项雄心勃勃的功能,我希望一旦完成,我就可以使用我以外的其他人.当我只使用这个功能时我可以忍受输出有点蹩脚,但如果我想要一些漂亮的输出怎么办?我正在寻找的基本上是这样的:

  • 一种打印控制台可读内容的方法
  • 能够访问打印的内容

更具体地说,假设我有三个标量的对象我想要打印:stat,dfreepval.目前,我这样做的方式是:

result <- list(statistic = stat, degrees = dfree, p.value = pval)
return(result)
Run Code Online (Sandbox Code Playgroud)

这样我可以通过运行来访问这些值,例如(调用该函数whites.htest):

whites.htest$p.value
Run Code Online (Sandbox Code Playgroud)

它有效,但输出有点难看.

> whites.htest(var.modell)
$statistic
[1] 36.47768

$degrees
[1] 30

$p.value
[1] 0.1928523
Run Code Online (Sandbox Code Playgroud)

如果我们运行这样的简单VAR模型:

> library(vars)
> data <- matrix(rnorm(200), ncol = 2)
> VAR(data, p = 2, type = "trend")

VAR Estimation Results:
======================= 

Estimated coefficients for equation y1: 
======================================= 
Call:
y1 = y1.l1 + y2.l1 + y1.l2 + y2.l2 + trend 

       y1.l1        y2.l1        y1.l2        y2.l2        trend 
-0.090102007 -0.060138062  0.126250484  0.014423006  0.003138521 


Estimated coefficients for equation y2: 
======================================= 
Call:
y2 = y1.l1 + y2.l1 + y1.l2 + y2.l2 + trend 

       y1.l1        y2.l1        y1.l2        y2.l2        trend 
 0.040118527  0.018274399 -0.132943318 -0.031235939  0.003242241
Run Code Online (Sandbox Code Playgroud)

输出看起来非常好.我已经看过它的底层代码(通过简单的运行VAR),但我找不到让它看起来像这样的好东西.

所以我的问题是,如何在仍然能够从函数中访问单个对象(即结果)的同时在控制台上打印出一些好的和可读的东西?

Aru*_*run 5

我可以想到的一种方法是美化输入(如果你正在编写更多函数,则获得更多控制)是创建一个类并修改show方法..这样的事情:

# set your class name and its representation is list here.
setClass( "stat_test", representation("list"))


# show method (here's how the output would be printed
# you can format to whatever you want... to show and how to show
setMethod("show", "stat_test", function(object) {
    cat("object of", class(object), "\n")
    cat("Estimated Coefficients\n")
    cat("  statistics\t\t\tdegrees\t\t\tp.value\n")
    cat("  ", object$statistics, "\t\t\t", object$degrees, "\t\t\t", object$p.value,"\n")
})


# now your actual function (here dummy of course)
my_fun <- function(x) {
    t <- list(statistics=1.5, degrees=30, p.value=1e-2)
    new("stat_test", t)
}

# now calling
w <- my_fun(2)
> w # you get

object of stat_test 
Estimated Coefficients
  statistics            degrees         p.value
  1.5            30              0.01 
Run Code Online (Sandbox Code Playgroud)

当然,您应该注意对齐.但这是一个基本想法.