首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >R和RStudio中控制台的不同显示

R和RStudio中控制台的不同显示
EN

Stack Overflow用户
提问于 2014-08-07 21:52:02
回答 1查看 1.1K关注 0票数 2

按照教程的代码,我定义了线性回归函数的类和方法。

代码语言:javascript
复制
data(cats, package="MASS")
linmodeEst <- function(x,y){

  qx   <- qr(x) # QR-decomposition
  coef <- solve.qr(qx,y) # solve(t(x)%*%x)%*%t(x)%*%y

  df     <- nrow(x)-ncol(x)
  sigma2 <- sum((y-x%*%coef)^2)/df
  vcov   <- sigma2 * chol2inv(qx$qr)

  colnames(vcov) <- rownames(vcov) <- colnames(x)

  list(coefficients = coef, vcov=vcov, sigma = sqrt(sigma2), df=df)
}

linmod <- function(x,...) UseMethod("linmod")

linmod.default <- function(x,y,...){
  x <- as.matrix(x)
  y <- as.matrix(y)

  est <- linmodeEst(x,y)

  est$fitted.values <- as.vector(x%*%est$coefficients)
  est$residuals     <- y - est$fitted.values
  est$call          <- match.call()
  class(est) <- "linmod"
  est
}

print.linmod <- function(x,...){
  cat("Call:\n")
  print(x$call)
  cat("\nCoefficients:\n")
  print(x$coefficients)
}

summary.linmod <- function(object,...){
  se <- sqrt(diag(object$vcov))
  tval <- coef(object)/se
  TAB <- cbind(Estimate = coef(object),
               StdErr = se,
               t.value = tval,
               p.value = 2*pt(-abs(tval), df=object$df))
  res <- list(call=object$call, coefficients=TAB)
  class(res) <- "summary.linmod"
  res
}

print.summary.linmod <- function(x,...){
  cat("Call:\n")
  print(x$call)
  cat("\n")

  printCoefmat(x$coefficients, P.value=TRUE, has.Pvalue=TRUE)
}
x = cbind(Const=1, Bwt=cats$Bwt)
y = cats$Hw
mod1 <- linmod(x,y)
summary(mod1)

因此,在summary.linmod <- function(object,...)中,我定义了表名:Estimate, StdErr, t.value, p.value。在R中,我得到标题中的所有名称,在RStudio中只有StdErr。为什么会发生这种事?

我的系统: Linux 64位,R3.1.1

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-07 23:31:02

?cbind的文档指出:“对于cbind (rbind),如果列(行)是类似于矩阵的,则列(行)名是从参数的冒号(行名)中提取的。”

在构造TAB时,需要将3个单列矩阵(即coef(object)tval2*pt(-abs(tval), df=object$df) )绑定到se (一个包含2个元素的非矩阵向量)。由于上面引用的行为,cbind使用矩阵的名称(空)来命名TAB的类似矩阵的列。

使用cbind.data.frame或简单的data.frame来构造TAB,您的摘要输出将具有预期的名称:

代码语言:javascript
复制
summary.linmod <- function(object,...){
  se <- sqrt(diag(object$vcov))
  tval <- coef(object)/se
  TAB <- data.frame(Estimate = coef(object),
                    StdErr = se,
                    t.value = tval,
                    p.value = 2*pt(-abs(tval), df=object$df))
  res <- list(call=object$call, coefficients=TAB)
  class(res) <- "summary.linmod"
  res
}


> summary(mod1)
# Call:
# linmod.default(x = x, y = y)
# 
#       Estimate   StdErr t.value p.value    
# Const -0.35666  0.69228 -0.5152  0.6072    
# Bwt    4.03406  0.25026 16.1194  <2e-16 ***
# ---
# Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25192888

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档