3

I'm looking for a way to adjust functions which usually show html tables in the viewer or browser in a way that they automatically insert the html in knitr documents like rnotebooks when called.

Specifically I want to change the way functions in the package sjPlot behave. At the moment they return an object with a $knitr attribute that has to be inserted manually and then produce an html table in the viewer:

`r sjt.frq(efc$e42dep, no.output=TRUE)$knitr`

One of these functions is sjt.frq. Is there a way to do this?

methodds
  • 85
  • 8

1 Answers1

3

From knit_print:

library(knitr)
a = 42
class(a) = "my_class"
knit_print.my_class = function(x,...){
    res = paste("{{", x,"}}")
    asis_output(res)
}
a

It works when I knit document but doesn't work with RNotebooks and doesn't work with sjt.frq. However with RNotebook works the following statement:

library(sjPlot)
library(sjmisc)
library(knitr)

data(efc)
asis_output(sjt.frq(efc$e42dep, no.output=TRUE)$knitr)
Gregory Demin
  • 4,596
  • 2
  • 20
  • 20
  • My experience has been it's best to get the character output and wrap it in `asis_output` as well – Benjamin Dec 15 '16 at 23:06
  • @Benjamin Do you mean `$output.complete` by "character output"? – Gregory Demin Dec 15 '16 at 23:13
  • I'm not familiar with the object. You need a character string of the HTML code. Putting a character string in `asis_output` is the same as putting the same string in `cat` with the chunk option `output='asis'` – Benjamin Dec 15 '16 at 23:20
  • Do you know an example where this works as described above? I just looked up ```DT::datadable``` and if I understand the code correctly they rely on ```htmlwidgets```: – methodds Dec 16 '16 at 09:41
  • htmlwidgets::createWidget("datatables", if (hideDataTable) NULL else params, package = "DT", width = width, height = height, elementId = elementId, sizingPolicy = htmlwidgets::sizingPolicy(knitr.figure = FALSE, knitr.defaultWidth = "100%", knitr.defaultHeight = "auto"), dependencies = deps, preRenderHook = function(instance) { data = instance[["x"]][["data"]] .... – methodds Dec 16 '16 at 09:42
  • sorry for the triple comment, I don't have enough reputation yet to edit.. – methodds Dec 16 '16 at 09:42
  • FYI `DT::datatable()` will eventually be converted to a character string and wrapped in `asis_output()`, although the actual implementation is a little complicated. I think it will be great if the author of sjPlot/sjmisc can provide a `knit_print` S3 method, so that its functions "just work" in knitr code chunks, otherwise you will have to either call `asis_output()`, or use `cat()` plus `results='asis'`. If the author needs an example, this email thread may be worth reading: https://groups.google.com/d/msg/knitr/xi0cE6UCb2A/1jb1Jw0EVaQJ – Yihui Xie Dec 18 '16 at 05:50