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.
By using invisible() function we can suppress the output.
The invisible() function in R Programming Language is used to make the printing statements invisible which means the printing statements will not appear.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With