1

Is it possible to instruct Rmarkdown to default all tables to my styled output? Here is my attempt:

---
title: 'Test Kable Global Styling'
output:
  html_document:
    df_print: kable
---

```{r}
library(knitr)
library(kableExtra)
kable <- function(data) {
   message("YES, IT BITES!  (not sortable, but styled.)\n")
   knitr::kable(data, digits=3) %>% kable_styling(bootstrap_options = "striped", full_width = F, position = "center")
}

```


## Testing

```{r}
d <- data.frame( x=1:3, y=rnorm(3) )
```

### Explicit Invokation

```{r}
kable(d)
```

### Implicit Invokation Fails

```{r}
d
```

The output looks like this:

sample failed output

[possibly related to How to set knitr::kable() global options in markdown for reuse, but defining my own kable function is not enough for Rmarkdown to select it.


thanks, mystery user for the complete solved update to the above problem. alas, could it generalize to :

```{r}
library(knitr)
library(DT); p <- function(...) DT::datatable(...)
knit_print.data.frame <- function(x, ...) asis_output(  paste( c("",p(x)) , collapse="\n" )  )
registerS3method("knit_print", "data.frame", knit_print.data.frame)
```

# Test Code

```{r}
d <- data.frame( x=1:3, y=rnorm(3) )
```

## Print

```{r}
p(d)

d
```

done
ivo Welch
  • 2,427
  • 2
  • 23
  • 31

1 Answers1

2

As you saw, How to set knitr::kable() global options in markdown for reuse describes how to do this with an explicit call to kable, but doesn't handle implicit displays. The way to do that is described in the ?knitr::knit_print help page. You need code like this early in your document:

kable <- function(data, ...) {
   message("YES, IT BITES!  (not sortable, but styled.)\n")
   knitr::kable(data, digits=3, ...) %>% kable_styling(bootstrap_options = "striped", full_width = F, position = "center")
}
knit_print.data.frame <- function(x, ...) {
  res <- paste(c("", "", kable(x)), collapse = "\n")
  asis_output(res)
}
registerS3method("knit_print", "data.frame", knit_print.data.frame)
user2554330
  • 37,248
  • 4
  • 43
  • 90
  • it works great, but it does not generalize!? `library(knitr); library(DT); p <- function(...) DT::datatable(...); knit_print.data.frame <- function(x, ...) asis_output( paste( c("",p(x)) , collapse="\n" ) ); registerS3method("knit_print", "data.frame", knit_print.data.frame); ` has `p(d)` work, but not `d`. can this be generalized? – ivo Welch May 05 '19 at 17:40
  • If `d` is a dataframe, it will work. If it is something else, you'll need to set the S3 method on that class as well. – user2554330 May 05 '19 at 20:01