How to find the appropriate print function for an object

Two weeks ago I learned to only implicitly print in R markdown files. Using print(x) overrides x's default print function (the one specific to the type of object it is) for the generic print function. One effect of this, for example, is that a tibble would be printed as plain text rather than as an interactive paged table.

Today I learned that if is a function, which means that only the final output is printed, just as in any other function. Therefore, to print multiple objects from one if statement, it is necessary to not implicitly print, but to wrap the object in a print function. (The solution proposed here is to continue implicitly printing, but to do so from a child document. I am not yet quite ready to add this complexity if I don't need to.)

⟹ How then, can I find the appropriate print function for a given object, e.g. rmarkdown:::print.paged_df for nibbles and print.ggplot for ggplots? (Default print() works just fine from within RStudio for Rmd files, but not when knit.)

As I explained in Interactive data frames in rmarkdown::render() like RStudio's Preview (or, printing in Rmd) - #2 by cderv usually using knitr::knit_print() would help for printing inside knitr chunk . See Custom Print Methods

Otherwise regarding your question about print.<class>, this is how methods works. You call print(object) and R will check the class to apply the right method. If object is a ggplot one, then it will call print.ggplot()

Learn more about S3 class : 13 S3 | Advanced R

Not that complex when you understand how this works, and what is the logic. This is to me the safest if you need to loop through object that prints with a complex representation (Htmlwidgets, HTML tables, ...)

This topic was automatically closed 45 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.