为什么函数不显示它应该显示的内容?

Why function does not display what it is supposed to display?

我在 R 中有以下代码,但输出有问题,它应该显示不同的东西。这是显示

Summary(x, y)

The total square sum is: 17.5The error square sum is: 0 
[[1]]
NULL

[[2]]
[1] "\n"

[[3]]
NULL

本来应该显示

The total square sum is: number1

The error square sum is: number2

请问可以查一下吗?

(这只是一个示例,实际上我必须展示更多东西the standar error is: number3, the variance is number4, etc..)

Summary <- function(x, y, print=TRUE) {
      p <- 2
      n <- length(x)

      x <- matrix(c(rep(1,n),x),n,p)
      bg <- solve(t(x)%*%x,t(x)%*%y)
      invx <- solve(t(x)%*%x)
      xty <- t(x)%*%y
      e <- y-x%*%bg
      SCT <- sum(y^2)-n*(mean(y)^2)
      SCE <- sum(e*e)

      result <- list(
        cat("The total square sum is:", SCT), 
        "\n", 
        cat("The error square sum is:", SCE, "\n"))
      return(result)      
}

x <- y <- 1:6
Summary(x, y)

list() 从对象创建列表,但 cat() 不是 return 对象,它只是打印到控制台。这就是为什么两个列表元素表示 NULL(它们是空的,而一个包含字符串 "\n"(实际对象)。

打印包含更多格式的文本可能很困难且不直观,但我发现可以在现有 R 代码中找到很多灵感和帮助。

print.lm()为例,该函数负责显示使用lm()的线性回归结果。

运行 stats:::print.lm 你会看到:

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

看起来有点忙,但还算不错。您会看到对 cat() 的每次调用都包含一个或多个字符串和分隔符(如 \n\t 换行和制表)按顺序排列, sep, 分隔符,指定在末尾。有时在 cat() 中有一个 paste() 调用,在这种情况下 paste() 只是 'prepares' 一些字符供 cat() 打印。我们还注意到,有多个 cat()print() 调用,混合和匹配已完成,没有问题。最后是 MrFlick 在评论中提到的 invisible() 的示例。此命令确保函数不会打印其参数(在本例中为 x),但您仍然可以将其分配给变量。

有了这些见解,我们可以改进 Summary() 吗?

Summary  <-  function(x, y, print=TRUE) {
    p  <-  2
    n <- length(x)

    xm <- matrix(c(rep(1,n),x),n,p)
    bg <- solve(t(xm)%*%xm,t(xm)%*%y)
    invx <- solve(t(xm)%*%xm)
    xty <- t(xm)%*%y
    e <- y-xm%*%bg
    SCT <- sum(y^2)-n*(mean(y)^2)
    SCE <- sum(e*e)

    results <- list(TSS=SCT, ESS=SCE, p=p, x=x, y=y)

    if (SCE == 0) warning("Error square sum is zero", call.=FALSE)

    if (print) {
        cat("Results for the variables", "\n\t",
            deparse(match.call()$x), " and ", deparse(match.call()$y),
            "\n\n", sep="")
        cat("The total square sum is: ", SCT, "\n\n",
            "The error square sum is: ", SCE, "\n\n", sep="")
        invisible(results)
    } else {
        results
    }      
}

看起来有点复杂。让我们测试一下。

Wendy <- Carlos <- 1:6

Summary(x=Wendy, y=Carlos)

Results for the variables
    Wendy and Carlos

The total square sum is: 17.5

The error square sum is: 0

Warning message:
Error square sum is zero