Many R functions return objects that are printed to the console in a special manner. For instance, t_results = t.test(c(1,2,3), c(1,2,4))
will assign a list
to the t_results
variable, but when I enter this variable in the console, or call it as print(t_results)
or show(t_results)
, it prints some plain text information (such as Welch Two Sample t-test...
etc.) instead of returning the actual list
. (This is a base R function, but I've seen this implemented in many custom user R packages just as well.)
My question is: how do I do this for objects created in my own custom R package? I've read several related questions and answers (e.g., this, this, and this), which do give a general idea (using setMethod
for my custom classes), but none of them makes it clear to me what exactly I need to do to make it work properly in a custom R package. I also cannot find any official documentation or tutorial on the matter.
To give an example of what I want to do, here is a very simple function from my hypothetical R package, which simply return a small data.frame
(with an arbitrary class name I add to it, here 'my_df_class'
):
my_main_function = function() {
my_df = data.frame(a = c('x1', 'y2', 'z2'),
b = c('x2', 'y2', 'z2'))
class(my_df) = c(class(my_df), 'my_df_class')
return(my_df)
}
I would like to have this printed/shown e.g. like this:
my_print_function = function(df) {
cat('My results:', df$a[2], df$a[3])
}
# see my_print_function(my_main_function())
What exactly has to be done to make this work for my R package (i.e., that when someone installs my R package, assigns the my_main_function()
results to a variable, and print
s/show
s that variable, it would be done via my_print_function()
)?