使用R打印环境
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用R打印环境相关的知识,希望对你有一定的参考价值。
我想编写一个函数,其输出是类myclass
的对象,带有vector,list,integer等等。与lm
function类似。我试图使用environment
,但是当我打印函数值时,结果是
#Term 1
> fit1
<environment: 0x00000000220d1998>
attr(,"class")
[1] "myclass"
但是,当我打印lm
函数时,结果是
> fit2
Call:
lm(formula = variable1 ~ variable2)
Coefficients:
(Intercept) variable2
49.0802 0.3603
我知道使用environment
访问$
的各个值。但我希望打印的对象与lm
函数相同,如图所示。
答案
那是你要的吗?
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("
Call:
", paste(deparse(x$call), sep = "
", collapse = "
"),
"
", sep = "")
if (length(coef(x))) {
cat("Coefficients:
")
print.default(format(coef(x), digits = digits), print.gap = 2L,
quote = FALSE)
}
else cat("No coefficients
")
cat("
")
invisible(x)
}
# now print
print(fit2)
# or
fit2
以上是关于使用R打印环境的主要内容,如果未能解决你的问题,请参考以下文章