Using Markdown shiny parameter in code and not only in figure generation - r

What is the most simple way to use R shiny in markdown to obtain an input from the user, say a number, and use it in the rest of the analysis?
All the example I have seen so far show how to use such input in generating a specific figure, but not in retaining this value as a variable to use in other code chunks.

You can use shiny inputs across chunks. Just think of the first chunk as your ui.R where you specify the input (e.g. numericInput("INPUT_ID", ...) and the second chunk as the server.R where you use the input as input$INPUT_ID.
Reproducible example:
---
output: html_document
runtime: shiny
---
# Chunk 1:
```{r, echo = FALSE}
numericInput("n", "How many cars?", 5)
```
# Chunk 2:
```{r, echo = FALSE}
renderTable({
head(cars, input$n)
})
```
Output:

Without an example of how you want the parameter outside of the renderTable to instruct the execution of your analysis it is hard to answer your question. But basically there are only two major options which come with a couple of sub-options.
Below is an update of my former answer:
1. You want to change the structure or layout of the flexdashboard depending on either:
1.1 User input
At the moment I do not see how this could be done, which does not mean that there is no solution - I might just be not aware of it.
1.2 User information (for example contained in the session info) For some special cases a workaround using the isolate function is possible, see my answer to a related question here for example.
1.3 Your data There are ways of nesting several Rmarkdown scripts to produce child templates as subpages based on the structure of the data that you read in (and might not know in advance). Here I found a very intriguing example.
2. You want to use a user input value within your analysis.
Although not clearly visible in the Rmarkdown structure, the analysis is taking place on the server part in shiny where you can use reactive and reactiveValues as they are. In this case BigDataScientist already answered your question. Of course you can use the input$n not only in renderTable but also in any other reactive expression or a reactiveValue which you can then use in some sort of render statement to show the users of your app the results of your analysis.

Related

Abstracts in rmarkdown that include numbers generated from the rmd itself?

So basically I have been writing a paper in Rmarkdown. The paper includes an abstract which has numbers/results that are generated from the code chunks within the markdown itself. Up to now, the workaround has been to place the abstract at the end of the paper, so that all the code chunks are run and the results generated before they are needed in the abstract.
Now that I am actually working on the final drafts, It would be ideal to have the abstract in the beginning. Is this even possible?
Thank you!
If your values won't change from run to run, one option is to use knitr::load_cache to load values from the cache of later chunks in your abstract section. The main downside is that this will only work on the second time knitting the document. The first time, load_cache will give NULL, then the later chunk will be run and the value cached. The second time, the cache will exist and will be used in the abstract.
```{r abstract}
y = knitr::load_cache('test-a', 'y')
print(y)
```
```{r test-a, cache=TRUE}
y = 2*pi
```
The first time you run it will give you this:
But knit it again and you'll see this:
This is kind of awkward, but was the recommended solution from yihui, the creator of rmarkdown. See this github issue: https://github.com/yihui/knitr/issues/868#issuecomment-68129294
You have to be careful with cached chunks – make sure that there is nothing that would change between runs and clear the cache before doing your final (2-step) knitting.

Is it possible to copy one (or 2, or 3) code chunks from one R Markdown document to another R Markdown document without copy/pasting?

I have read previously asked similar questions here, here, and here (among many more).
Unfortunately, none of the solutions offered to those questions seem to solve my issue.
I tried the function written by #bryanshalloway here but that did not have the desired result.
For more context, I am producing scientific manuscripts using an R Markdown workflow. I perform EDA in one notebook and later come back to write the manuscript in a different notebook. I import the data, wrangle it, create tables, and do some basic visualizations in the EDA notebook and include narrative text (mostly for myself).
I then create a separate notebook to write the manuscript. To keep it reproducible, I want to include all of the steps from the EDA with respect to data import, tidying, and wrangling, however I do not need the commentary that went along with it. Additionally, I may want some (but definitely not all) of the tables and basic visualizations I created during the EDA, but I would need to build them up substantially to get them publication ready.
My current workflow is just copying and pasting the relevant code chunks and then adding to those where necessary for tables and figures (i.e., adding labels and captions to a ggplot).
Is there a way to "source" these individual code chunks from one R Markdown file/R Notebook into another? Perhaps using knit_child (but not bring the entire R Markdown file into the current parent file)?
I would like to avoid copying the desired code chunks into separate R scripts.
Thanks!
It is very possible with knitr purl and spin:
Ok lets say this is your initial Rmarkdown report:
call the file report1.Rmd
---
title: Use `purl()` to extract R code
---
The function `knitr::purl()` extracts R code chunks from
a **knitr** document and save the code to an R script.
Below is a simple chunk:
```{r, simple, echo=TRUE}
1 + 1
```
Inline R expressions like `r 2 * pi` are ignored by default.
If you do not want certain code chunks to be extracted,
you can set the chunk option `purl = FALSE`, e.g.,
```{r, ignored, purl=FALSE}
x = rnorm(1000)
```
Then you go to the console and purl the file:
> knitr::purl("report1.Rmd")
this creates an R file called report1.R in the same directory you are in,
with only the chunks that are not purl=false.
Its an simple R script looking like this:
## ---- simple, echo=TRUE----------------------------------------------------------------------------
1 + 1
Lets rename the file for safety purposes:
> file.rename("report1.R", "report_new.R")
Finally lets spin it back to report_new.Rmd :
> knitr::spin("report_new.R", format = "Rmd", knit=F)
This gives you a new Rmd file called report_new.Rmd containing only the relevant chunks and nothing else
```{r simple, echo=TRUE}
1 + 1
```

R markdown to use variables existing in the environment and not run code again

Perhaps I am not using R markdown properly, but my first line of code load a very large data set and then does analysis. Every time I knit the pdf to see what it looks like, it runs all the code again, this takes quite a while. The data is already stored in the environment so is there a way of getting R to not run all the code again but display the pdf with the alterations made?
In case loading your very large data set is the problem, try special packages for reading your data like readr.
Alternative, since you working on the design or representation in you PDF, you can work on a subset of your data like only on the first 100000 rows.
Otherwise, I use the following code in my first code chunk
library(knitr)
# global setting to create this document
opts_chunk$set(cache=TRUE,
echo=TRUE, # set to FALSE to remove the code output
warning=FALSE,
message=FALSE)
so I don't need to set cache=TRUE in each chunk.
Hope this helps.
My set of tricks is evolving:
a parameter to use on the chunk's eval=params$do.readdata
this type of construct:
if (exists('<name of data table>') {
load(<file>, verbose=TRUE) or st_read_feather...
} else {
<read in data>
}
Until recently, i was using a cache option on the chunk, but recently learned that putting the import and processing of data in a function in order to remove it from the global environment (if memory is an issue) and return a smaller subset or result that is needed later. So, caching may not be an option.

Tangle knitr code blocks into not one but several files

I am a new user to knitr. I know that knitr can "tangle out" (taken from the Literate programming community) or extract source code blocks into an R script file. Being an org-mode-user, I am used to being able to specify a specific file for each code block, with potentially the same file for different blocks. When "tangling" or extracting source in org-mode, instead of having one output code file, several code files are produced (this helps with modularity in large projects).
I wonder if something similar is possible in knitr? Can I specify the output file in knitr on a block by block basis?
There are at least two different readings of your question, each requiring slightly different workflows.
If each chunk is going to be written into a separate output document, then to assist modularity, you should split the reporting part down into multiple documents. Since knitr supports child documents, you can always recombine these into larger documents in any combinations that you like.
If you want conditional execution of some chunks, and there are a few different combinations of conditions that can be run, use an R Markdown YAML header, and include a params element.
----
params:
report_type: "weekly" # should be "weekly" or "yearly"
----
You can set which chunks are run by setting the eval and include chunk options.
```{r, some_chunk, eval = params$report_type == "weekly", include = params$report_type == "weekly"}
# chunk contents
```

Displaying dataframes in R Markdown

I can't find a method to remove the hash marks and row numbers from dataframes outputted to a word document in R markdown. I'd like to be able to present only the data without those features
The knitr website and specifically the page on Chunk options suggests the use of a separate chunk (before your want to display a data.frame in this manner) to change the default for the chunk option comment, perhaps like this:
```{r global_options}
opts_chunk$set(comment = NA) # default value is '##'
```
to disable the inserting of comment characters on output. Realize that this setting of the comment option is applicable to all chunks that follow this chunk; this chunk itself will not be affected by it.
This does give the textual representation of the data.frame (as if it were on the terminal), and not a more refined representation. I second #PierreLafortune's suggestion to look at knitr::kable.
Check out the sjPlot package and specifically the view_df function

Resources