RStudio chunk render=function(x,...){} not working

35 views
Skip to first unread message

Malcolm Cook

unread,
Mar 13, 2018, 2:44:03 AM3/13/18
to knitr
Hello,

I am finding that chunk render functions do not work in my hand in RStudio.  In fact they seem to be ignored or un-implemented.

The following r chunk results in my constant string being rendered as a data.table quite nicely:

```{r}
library(magrittr)
library(DT)
csvstr2dt<- function(x,...) {x %>% textConnection() %>%  read.csv() %>% DT::datatable()}

'a,b,c
1,2,3
4,5,6' %>% csvstr2dt
```

I would now like to use csvstr2dt as a chunk render function to do the same.

However,  in the below, the render function seems to be ignored.

```{r render=csvstr2dt}
'a,b,c
1,2,3
4,5,6'
```
[1] "a,b,c\n1,2,3\n4,5,6"

Do I have incorrect understand of what to expect from a render function on a code block like this?

Thanks!

Malcolm Cook

Malcolm Cook

unread,
Mar 13, 2018, 6:34:41 PM3/13/18
to knitr
I figured out the problem with my understanding of how the render works.

My problem was the when the render function is called, my custom render function is not available to it as it is defined in file itself.

This works:

```{r, render=function(x,...)   knitr::knit_print(kable(read.csv(textConnection(x))))}
'a,b,c
1,2,3
4,5,6'
```

So, I understand that if I want to use custom render functions, I should put them in a package, say knitrExtras, and contrive to load in addition to rmarkdown

For example, the following shell function

    function rendeRmd () { Rscript -e 'library(rmarkdown)' -e 'csvstr2dt=function(x,...) knitr::knit_print(kable(read.csv(textConnection(x))))' -e 'render(commandArgs(trailingOnly=TRUE))' "$@" ; }

allows me to call

    rendeRmd t1.Rmd

and  render Rmd files which using cvstr2dt as custom block rendering function.

I understand even better will be to put my custom render functions in a package.  At least now I understand my misconception.

All is well!  Thanks for knitr!
Reply all
Reply to author
Forward
0 new messages