按照教程的代码,我定义了线性回归函数的类和方法。
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

发布于 2014-08-07 23:31:02
?cbind的文档指出:“对于cbind (rbind),如果列(行)是类似于矩阵的,则列(行)名是从参数的冒号(行名)中提取的。”
在构造TAB时,需要将3个单列矩阵(即coef(object)、tval和2*pt(-abs(tval), df=object$df) )绑定到se (一个包含2个元素的非矩阵向量)。由于上面引用的行为,cbind使用矩阵的名称(空)来命名TAB的类似矩阵的列。
使用cbind.data.frame或简单的data.frame来构造TAB,您的摘要输出将具有预期的名称:
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 ‘ ’ 1https://stackoverflow.com/questions/25192888
复制相似问题