Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding a result of a function in R

Tags:

r

I created a function that has four output arguments, for example:

myfuction<-function(...){     
    #Inside the function I created four results A, B, C, and D.    
    A = ...    
    B = ...    
    C = ...    
    D = ...     
    z<-list(MacKinnon=A,regression=B,proof=C, res=D)    
    return(z)
}

The result D corresponds to a vector of numbers that respresents the residuals of a regression.

My question is How can I hide this result without removing it? That is, I want that when I run the function, the results A, B, and C appear, but not the result D.

And if I want to access the result D, I have to do something like this:

X <-myfuction (...)
X$res

to be able to observe the residual.

like image 396
Carlos David Avatar asked May 23 '16 16:05

Carlos David


People also ask

How do I suppress the output of a function in R?

By using invisible() function we can suppress the output.

What does invisible mean in R?

The invisible() function in R Programming Language is used to make the printing statements invisible which means the printing statements will not appear.


1 Answers

I would just use an S3 class. Basically, just tag the object z with a particular class

myfunction <- function(){     
  #Inside the function I created four results A, B, C, and D.    
  A = 10;B = 20;C = 30; D = 40     
  z = list(MacKinnon=A, regression=B, proof=C, res=D)    
  class(z) = "my_fun" # Tagging here
  return(z)
}

Create an S3 print function for my_fun

print.my_fun = function(x, ...) print(x[1:3])

Then

R> x = myfunction()
R> x
$MacKinnon
[1] 10

$regression
[1] 20

$proof
[1] 30

But

R> x$res
[1] 40

gives you want you want.


A couple of comments/pointers.

  • Typically when you assign the class, you would use something like

    class(z) = c("my_fun", class(z))
    

    however, since we just created z in the line above, this isn't needed.

  • Currently the print method strips away any additional classes (in the example, there is only one class, so it's not a problem). If we wanted to maintain multiple class, we would use

    print.my_fun = function(x, ...) {
      x = structure(x[1:3], class = class(x)) 
      NextMethod("print")
    }
    

    The first line of the function subsets x, but maintains all other classes. The second line, then passes x to the next print.class_name function.

like image 119
csgillespie Avatar answered Sep 20 '22 13:09

csgillespie