I have the followin markdown:
---
title: "My report"
output: html_document
---
```{r setup, include=FALSE}
library(DT)
my_func <- function(x) {
#DT::datatable(x)
print(DT::datatable(x))
nrow(x)
}
```
```{r}
x <- my_func(mtcars)
print(x)
```
I want to display a DT from inside the function, but this function performs some calculations that I'm interested in the output of. So far it doesn't display the table. How can I force markdown to generate a table without returning it?
What about something like this:
---
title: "My report"
output: html_document
---
```{r setup, include=FALSE}
library(DT)
my_func <- function(x) {
res <- list(dt = DT::datatable(x),
nr = nrow(x))
class(res) <- "myfun"
invisible(res)
}
```
```{r}
x <- my_func(mtcars)
x$nr
```
```{r}
x$dt
```
Related
I'd like to change the fig.cap chunk option within a chunk for a knitr document. I tend to write a lot of reporting code that looks like the following to take a plot out of a tibble and use the associated caption with it.
```{r fig, fig.cap=d_plot$caption}
d_plot <- [load the plotting tibble from prior work]
knit_print(d_plot$figure[[1]])
```
Something similar to what I'd like to do is the following, but where the caption actually shows up. And, better yet would be if it would modify fig.cap and fig.scap with the possibility of having multiple knit_print() calls with multiple sets of figures.
---
title: "Untitled"
author: "William Denney"
date: '2022-04-19'
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo=FALSE, warning=FALSE, error=FALSE)
library(tidyverse)
library(knitr)
```
# Test
```{r functions, include=FALSE}
knit_print.fig_n_cap <- function(x) {
lapply(x$figure, knit_print)
opts_chunk$set(fig.cap=x$caption)
}
as_fig_n_cap <- function(x) {
stopifnot(is.data.frame(x))
stopifnot("figure" %in% names(x))
stopifnot("caption" %in% names(x))
class(x) <- c("fig_n_cap", class(x))
x
}
p <- ggplot(data.frame(x=1:3, y=1:3), aes(x=x, y=y)) + geom_line()
d <- as_fig_n_cap(tibble(figure=list(p), caption="My caption"))
```
```{r}
knit_print(d)
```
I'm trying to incorporate an Rmd I have been using into a flexdashboard. I'm curious if it is possible to isolate an uploaded file and use it as-is rather than writing a bunch of reactive functions. If this is my template, is it possible to get a static object named df that the child document can go ahead and run with?
---
title: "help"
runtime: shiny
output:
flexdashboard::flex_dashboard:
orientation: columns
---
```{r}
fileInput("data", "select data")
df <- isolate(input$data)
```
```{r, child="some_code.Rmd"}
```
My real example does something completely different but let's say some_code.Rmd looks like this:
---
title: "some code"
output: html_document
---
```{r packages, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE)
library(tidyverse)
```
The data looks like this:
```{r}
as_tibble(df)
```
The numeric data can be summarized with the following means
```{r}
df |>
summarise(across(where(is.numeric), mean)) |>
gather()
```
This ended up working:
knitr::knit() + markdown::markdownToHTML() + HTML() ---> renderUI()
---
title: "help"
runtime: shiny
output:
flexdashboard::flex_dashboard:
orientation: rows
---
Sidebar {.sidebar}
==============================================
```{r file-input}
fileInput("data", "select data")
```
Row
==============================================
```{r knit-child}
observeEvent(input$data, {
df <- isolate(read.csv(input$data$datapath))
new_env <- list2env(list(df = df))
output$res <- renderUI({
knitr::knit("some_code.Rmd", quiet = TRUE, envir = new_env) |>
markdown::markdownToHTML() |>
HTML()
})
})
uiOutput("res")
```
After upgrading Rstudio to 1.4 version, when I render this rmarkdown doc
---
title: "Raw HTML"
output: html_document
---
```{r setup, include=FALSE}
library(knitr)
library(htmltools)
knitr::opts_chunk$set(echo = F)
```
```{r}
f <- function(text){
cat(asis_output(htmltools::htmlPreserve(paste("<span style=\"color:green\">", text, "</span>"))))
return(0)
}
```
```{r}
x <- f('Hello!')
```
I get this html doc
But before the update this code worked as expected, rendering this html doc
How can I get the second html doc?
cat removes the knit_asis class.
You can either avoid cat or use results='asis' chunck option :
---
title: "Raw HTML"
output: html_document
---
```{r setup, include=FALSE}
library(knitr)
library(htmltools)
knitr::opts_chunk$set(echo = F)
```
```{r}
side.effect <- function(text){
cat(asis_output(htmltools::htmlPreserve(paste("<span style=\"color:green\">", text, "</span>"))))
return(0)
}
direct <- function(text){
asis_output(htmltools::htmlPreserve(paste("<span style=\"color:green\">", text, "</span>")))
}
```
```{r}
direct('direct Hello!')
```
```{r,results ='asis'}
x <- side.effect('side effect Hello!')
```
I am currently writing on a report with rmarkdown and therefore I want to create sections inside a r code chunk. I figured out that this is possible with the help of cat() and results="asis". My problem with this solution is, that my R code results and code isn't properly displayed as usual.
For example
---
title: "test"
output: pdf_document
---
```{r, results='asis'}
for (i in 1:10) {
cat("\\section{Part:", i, "}")
summary(X)
$\alpha = `r X[1,i]`$
}
```
pretty much does the trick, but here there are still two problems:
the R output for summary() is displayed very strange because I guess it`s interpreted as LaTeX code
I can't use LaTeX formulas in this enviroment, so if I want every section to end with a equation, which also might use a R variable, this is not possible
Does somebody know a solution for some of these problems, or is there even a workaround to create sections within a loop and to have R code, R output and LaTeX formulas in this section? Or maybe at least one of those things?
I am very thankful for every kind of advice
You can do what you are after inline without relying as much on code blocks.
As a minimal example.
---
title: "test"
output: pdf_document
---
```{r sect1_prep, include=FALSE}
i <- 1
```
\section{`r paste0("Part: ", i)`}
```{r sect1_body}
summary(mtcars[, i])
```
$\alpha = `r mtcars[1, i]`$
```{r sect2_prep, include=FALSE}
i <- i + 1
```
\section{`r paste0("Part: ", i)`}
```{r sect2_body}
summary(mtcars[, i])
```
$\alpha = `r mtcars[1, i]`$
Produces...
If you really want to have a section factory, you could consider pander.
---
title: "test"
output: pdf_document
---
```{r setup, include=FALSE}
library(pander)
panderOptions('knitr.auto.asis', FALSE)
```
```{r, results='asis', echo=FALSE}
empty <- lapply(1:10, function(x) {
pandoc.header(paste0("Part: ", x), level = 2)
pander(summary(mtcars[, x]))
pander(paste0("$\\alpha = ", mtcars[1, x], "$\n"))
})
```
which produces...
remove summary table format example
---
title: "test"
output: pdf_document
---
```{r setup, include=FALSE}
library(pander)
panderOptions('knitr.auto.asis', FALSE)
```
```{r, results='asis', echo=FALSE}
content <- lapply(1:10, function(x) {
head <- pandoc.header.return(paste0("Part: ", x), level = 2)
body1 <- pandoc.verbatim.return(attr(summary(mtcars[, x]), "names"))
body2 <- pandoc.verbatim.return(summary(mtcars[, x]))
eqn <- pander_return(paste0("$\\alpha = ", mtcars[1, x], "$"))
return(list(head = head, body1 = body1, body2 = body2, eqn = eqn))
})
writeLines(unlist(content), sep = "\n\n")
```
I want to set the chunk option "eval" based on a list of chunk names. Is there a function to get the chunk name in knitr, e.g. chunk_name?
This is my minimum example with fake function name "chunk_name".
---
output: html_document
---
```{r setup}
eval_chunks <- c('chunk1')
```
```{r chunk1, eval=chunk_name() %in% eval_chunks}
plot(cars)
```
```{r chunk2, eval=chunk_name() %in% eval_chunks}
plot(cars)
```
Thanks for any suggestions. Please let me know if my question is not clear.
Knitr provided labels inside a chunk since 2012 (need more Google, https://github.com/yihui/knitr/issues/73).
This is my sample Rmd file:
---
output: html_document
---
```{r setup}
library(knitr)
eval_chunks <- c('chunk1', 'chunk3')
```
```{r chunk1, eval=opts_current$get("label") %in% eval_chunks}
print(opts_current$get("label"))
```
```{r chunk2, eval=opts_current$get("label") %in% eval_chunks}
print(opts_current$get("label"))
```
```{r chunk3, eval=opts_current$get("label") %in% eval_chunks}
print(opts_current$get("label"))
```
I think this solution is imperfect because it requires a bit of care in making sure the correct chunks are evaluated, but it gets around the problem that chunk options are evaluated before hooks are called. In short, it doesn't use a hook, but instead uses the fact that chunk options can be R expressions. In this case, a function e() is used that relies on a global counter variable to dictate whether a particular chunk should be evaluated. Because chunks are evaluated in order, this works. In the below example, chunk1 and chunk3 are evaluated, but the others are not.
---
output: html_document
---
```{r setup}
library("knitr")
.i <- 2 # `setup` is the first chunk, so start at 2
.x <- all_labels() %in% c("chunk1", "chunk3")
e <- function(){
d <- .x[.i]
.i <<- .i + 1
d
}
```
```{r chunk1, eval=e()}
x <- 1
x
```
```{r chunk2, eval=e()}
x <- 2
x
```
```{r chunk3, eval=e()}
x <- 3
x
```
```{r chunk4, eval=e()}
x <- 4
x
```