我想这个问题在某个地方被问过。虽然我找不到一个。请帮帮我。我需要输出一个列表,但可能只显示列表的第一个元素,而其他元素不可见。虽然可以访问它们。
请允许我举一个例子。
s=lm(iris)
s
Call:
lm(formula = iris)
Coefficients:
(Intercept) Sepal.Width Petal.Length Petal.Width
2.1713 0.4959 0.8292 -0.3152
Speciesversicolor Speciesvirginica
-0.7236 -1.0235
length(s)
[1] 13
Run Code Online (Sandbox Code Playgroud)
在这里我们看到,当使用lm函数时,输出是一个长度为 13 的列表。我们可以s通过简单地使用美元符号来访问我们想要的所有元素。但同时我们只看到调用和系数,我们看不到所有其他元素,如残差、拟合值等。我如何在我的函数上实现这个?
对于上面的示例,返回的对象属于类 lm。我想编写一个不一定输出 lm 对象的函数。
谢谢
您所要做的就是定义一个新类和相应的print方法。类似于以下内容,我在其中定义了一个 class Onyambu。
set.seed(736) # make the code reproducible
x <- structure(list(
A = sample(0:1, 20, TRUE),
B = sample(letters[1:5], 20, TRUE),
M = 1:5,
N = 6:10,
X = rnorm(10),
Y = rexp(12)
),
class = "Onyambu" # This is the new class
)
# Before the print method for class "Onyambu" is defined
# it prints like a normal list
x
print.Onyambu <- function(x){
cat("Sum: ", sum(x[[1]]), "Mean: ", mean(x[[1]]), "\n")
print(table(x[[2]]))
invisible(x)
}
# After print.Onyambu is defined, it prints like we want it to
x
#Sum: 13 Mean: 0.65
#
#a b c d e
#3 3 6 5 3
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
383 次 |
| 最近记录: |