如何在仅显示列表的一部分的同时输出具有不可见项R的列表

时间:2017-10-23 05:46:17

标签: r

我猜这个问题已被问到某个地方。虽然我找不到一个。请帮帮我。我需要输出一个列表,但只显示列表的第一个元素,而其他元素是不可见的。虽然有人能够访问它们。

请允许我举一个例子。

 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

这里我们看到,当使用lm函数时,输出是一个长度为13的列表。我们可以通过简单地使用美元符号来访问s所需的所有元素。但同时我们只看到调用和系数,我们没有看到所有其他元素,如残差,拟合值等。我怎样才能在我的函数上实现它?

对于上面的示例,返回的对象是类lm。我想编写一个不一定输出lm对象的函数。

谢谢

1 个答案:

答案 0 :(得分:3)

您所要做的就是定义一个新类和相应的print方法。类似于以下内容,我定义了一个类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