如何在调用函数时返回多个对象并仅显示返回的一部分

时间:2018-07-21 15:11:25

标签: r

对于用户定义的函数,如果有多个对象要返回,我将使用list。

但是,并非所有信息都同样重要。 例如,我正在编写一个函数,该函数通过迭代估算3个参数。最终的收敛结果是最重要的,因此调用函数后,我希望看到3个数字。尽管有时需要迭代的历史记录(估算的所有步骤),但是始终打印出所有步骤会占用整个屏幕。

当前,我使用list返回3个矩阵,其中包含所有步骤。 有没有一种方法可以使函数返回相同的结果,但是当我调用该函数时,它仅显示最后3个收敛的估计。如果我需要估算步骤,则可以使用$来获取它们。看起来像这样:

MyEstimate(arg1, arg2, ...)      # only show 3 final estimates

model <- MyEstimate(arg1, arg2, ...)
model$theta1                     # show all steps of estimates of theta1

基本上,我希望它像'lm'函数一样工作:     显示一些重要的内容,例如参数估计;     不显示,但仍然可以访问,例如设计矩阵X


我认为没有简单的答案。 为此,我应该学习什么?

2 个答案:

答案 0 :(得分:0)

您可以使用print在调用函数时始终打印您感兴趣的值,同时将所有信息保留在返回的对象中。

> myFun <- function(){
   a <- sample(1:10, 10, TRUE)
   b <- sample(1:10, 10, TRUE)
   c <- sample(1:10, 10, TRUE)

   # Print Last value
   print(tail(a,1))
   print(tail(b,1))
   print(tail(c,1))
   return(list(a = a, b=b, c=c))
 }

> Obj <- myFun()
[1] 10
[1] 5
[1] 2

> Obj
$a
 [1]  2  9  4  7  3  2  2  5  1 10

$b
 [1] 6 4 9 8 8 9 2 8 6 5

$c
 [1] 2 6 9 2 6 7 8 2 6 2

答案 1 :(得分:0)

您可以使用S3类机制使函数MyEstimate返回由您组成的特殊类的对象,并为该类编写一个print方法。您将 subclass "list"

如果此特殊类名为"tautology",则应编写方法print.tautology。遵循以下原则:

print.tautology <- function(x){
  h <- tail(x[[1]], 3)
  print(h)
  invisible(h)
}


MyEstimate <- function(x, y, ...){
  res <- list(theta1 = 1:10, beta2 = 11:15)
  class(res) <- c("tautology", class(res))
  res
}

arg1 <- 1
arg2 <- 2
MyEstimate(arg1, arg2)      # only show 3 final estimates
#[1]  8  9 10

model <- MyEstimate(arg1, arg2)
model$theta1                   # show all steps of estimates of theta1
#[1]  1  2  3  4  5  6  7  8  9 10