How to use a shiny app inside rmarkdown file? - r

How can i add a shiny app inside the rmarkdown file? I have a file named app.r (contains the shiny app) and another file rep.rmd. i saw something like
shinyAppDir(
system.file("app.R", package = "shiny"),
options = list(
width = "100%", height = 550
)
)
To use the shinyapp inside my rmarkdown file.
But it shows this error in console could not find function "shinyAppDir"
How can i use my shiny app inside the rmarkdown file?
EDIT:
It's not really a solution as this is more like a workaround, but what i did is to actually put all my files (app.R and report.rmd) into the same folder with the library shiny, and now it detects it. Still, one problem would be that if you have many libraries included in your app.r , it might collapse and terminate R session.

Related

Is it possible to knit an R Markdown file only to a preview window/pane in RStudio without saving an html file?

I would like to keep the base folder of my R Markdown project tree as uncluttered as possible and still use the Knit button in RStudio to see some results as an HTML output in the RStudio's preview window. However, every time I knit, an HTML file is created to the base folder along my .Rmd files.
My folder structure might look like this:
If I've understood correctly - and do please correct me if I'm wrong - it is not very straightforward to output the HTML files to an upstream folder (here:"results" folder) from an R Markdown file by pressing the Knit button, so I would be willing to:
prevent the creation of HTML files altogether,
still see the results in an HTML format in RStudio's preview window, and
only when I'm really willing to save an HTML file, save (export) such a file and (manually) transfer it to the results folder.
So, if there is no easy way of directing the HTML files to the "results" folder, can I prevent the creation of HTML files altogether and only preview the results in the preview window?
I don't know of a way to attach this to the knit button, but you could write a function that does this:
get the current file open in the edit pane. This answer gives details on that.
run rmarkdown::render() with the output_dir argument set the way you want.
You can attach this function to a keyboard shortcut in RStudio using these instructions.
Here's a simple version of the function:
knit2 <- function(filename = rstudioapi::getSourceEditorContext()$path,
output_dir = tempdir()) {
result <- rmarkdown::render(filename, output_dir = output_dir)
getOption("viewer")(result)
}
Simply call knit2(), and the output will be written to tempdir(), which means the preview will appear in the Viewer pane. If you want it to write to "results", call it as
knit2(output_dir = "results")
If that's not a subdirectory of tempdir(), the preview will appear in an external browser.

R shiny: read csv a file in UI

Context
I built a shiny app in R that i can run as i want. It means i can insert read.csv before UI and then use the file loaded in R in the UI. Now i need to create a shortcut in desktop so i need to insert the read.csv in the UI. But i can't insert a read.csv in the UI. So i need to know how can i load a file and use it in UI so i can run "C:\Program Files\R\R-3.3.2\bin\R.exe" -e shiny::runApp('C:/Users/Desktop/Cal_pro')
In the Cal_pro folder i put my ui.R and server.R
Does anyone has an idea ?

knitr with Shiny: temporary directory

I've built a Shiny app that estimates a model; I would like the user to be able to download a summary of the model in a pdf format when the estimation is finished. I've included a download button in the app as follows:
output$download_estimation = downloadHandler(
filename = "report.pdf",
content = function(file) {
withProgress(message = 'Generating...', {
rmarkdown::render('report_model.Rmd', output_file = file)
})
})
The file 'report_model.Rmd' uses a custom LaTeX template. The issue is that, whenever I click the download button in Shiny, knitr evaluates the chunks but after that I get a LaTeX error of 'Undefined control sequence.' This occurs because the paths to figures in the report within \includegraphics{} are incorrectly specified: instead of using only forwards slashes in the file path, knitr produces a combination of backward and forward slashes, for example
\includegraphics{C:\Users\admin\AppData\Local\Temp\Rmksdfj0568\report_model_files/figure-latex/unnamed-chunk-5-1.pdf}.
When I knit the exact same document from RStudio outside of Shiny, this does not happen because the .tex is not produced in the temporary directory but rather in the directory where the .Rmd is placed and I get the correct path as
\includegraphics{report_model_files/figure-latex/unnamed-chunk-5-1.pdf}.
Moreover, when I don't use the custom template but rather the Pandoc built-in one, everything works fine. I was, however, unable to figure out why the use of custom template makes the difference. Is there a way to fix this?
The solution to this issue, at least in this specific case, is to include
```{r, echo = FALSE, include = FALSE}
knitr::opts_knit$set(base.dir = normalizePath(tempdir(), winslash = '/'))
knitr::opts_chunk$set(fig.path = "figure/")
```
in the beginning of the 'Rmd' file that uses the custom template. This works when the app is run locally, the solution may not work when the app is deployed.

How to split Shiny app code over multiple files in RStudio? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I tried to split code for a shiny application over different files, but can't get this to work decently in Shiny. My attempt can be found in this demo
How can I split up my code over different files, but still keep the 'Run App button ' and have 'Code Completion' back in RStudio?
if not ! can i integrate shiny with Visual Studio ?
Yes, you can achieve that very easily in the same way you do that with every other project in RStudio: by using the R mechanisms provided to achieve that:
define functions and/or objects in separate files.
use source() in your main file to load their definitions
Code completion for shiny functions only occurs in RStudio when the shiny package is loaded using library(shiny). The 'Run App' button will be visible for the main file in the application. In the example below, that would be the app.R file. So if you want to run your app from within RStudio, you always have to go back to the main file.
standard example
An example :
In a file app.R you put:
library(shiny)
source('myUI.R', local = TRUE)
source('myServer.R')
shinyApp(
ui = myUI,
server = myserver
)
This code does nothing else but initiate the objects myUI and myserver and call the app.
The file myUI.R contains
source('Tabs.R')
myUI <- shinyUI({
fluidPage(
tabsetPanel(
Tab1,
Tab2
)
)
})
This file defines the UI object used in app.R. The function tabsetPanel takes a number of tabPanels as arguments. These tabPanels are created in the following file (Tabs.R), so that one has to be sourced before the UI is constructed.
The file Tabs.R contains:
Tab1 <- tabPanel("First Tab",
selectInput("select",
"Choose one",
choices = letters[1:3],
selected = 'a'))
Tab2 <- tabPanel("Second Tab",
textOutput('mychoice'))
This file creates the tabPanel objects to be added to the tabsetPanel. In my own code, I store every tabPanel definition in a separate file.
The file myServer.R contains:
myserver <- function(input,output,session){
output$mychoice <- renderText(
input$select
)
}
And if you want, you can again create separate files with functions that can be used inside the server function. But you always have to follow the classic R logic: assign things to an object and refer to that object at the position you want to insert it.
You can also source code directly inside the server() function. In that case you should source locally using source(..., local = TRUE), so the created objects are contained inside the server function. See also : https://shiny.rstudio.com/articles/scoping.html
Using modules
If you want to take it up a notch and reuse a certain logic and layout (eg a plot option control panel that should be attached to some plots), you should go to modules. (see also http://shiny.rstudio.com/articles/modules.html )
Modules can again be stored in a separate file, and that file sourced in the app.R file you have.
#Joris Meys 's answer covered the topic of splitting shiny code into files. Though one part of the question is to use the run app button, which may not be available even if the organization make a valid shiny app.
If you search this question you can find this issue, then following to the commit made in that issue you can find what's the rule to have a run app button, and this function about isShinyAppDir, this function of shinyfiletype:
Basically any folder have ui.R, server.R, app.R, global.R, www folder will be considered as shiny folder(the detailed conditions are more complex, see source code), then the above 4 files will have run app button.
One thing I noticed is that usually you can keep the app running, make some changes then reload app to see the changes, but if you sourced other file, reload app button will not reload changes in that sourced file.

Embedding Shiny app in knitr document

I have a shiny app which has a ui.R, server.R and global.R. The app directory (name = dash) contains the folder 'data' in which the dataset resides. Also, this app folder is inside the project's working directory.
In global.R I read the data as:
dash <- read.table("data/ntraj1acc.txt", sep=",", header=T)
This app works fine. Now, I am trying to embed it in a ioslides presentation which otherwise works good. The example in External Applications section on rmarkdown website also works perfect in my presentation. But when I replace the path in system.file to my app, I get the error:
No Shiny application exists at the path ""
Here is how I replaced the path:
shinyAppDir(
system.file("dash", package="shiny"),
options=list(
width="100%", height=700
)
)
After the error, I tried following:
shinyAppDir(
"C:/Users/durraniu/Documents/Trajectory-one/dash",
options=list(
width="100%", height=700
)
)
But then I got a new error:
object 'dash' not found
Which means that it is not parsing global.R.
How can I fix this problem?
I successfully embeded an application within an interactive shiny document with the following rmarkdown chunk:
```
shinyAppDir("D:/Documents/OneDrive/Notes/R-Explore/shiny/01-ages/",
options=list(
width="100%", height=550
)
)
```
All 3 files: the ui.R, server.R, and test.Rmd are at the above absolute path
system.file("dash", package="shiny") is definitely not going to work, that's looking for a folder named "dash" inside the shiny package itself, which obviously doesn't exist.
Also we have a limitation in RMarkdown that it doesn't call global.R for embedded Shiny apps, sorry that this fact appears not to have made it into the documentation. https://github.com/rstudio/rmarkdown/issues/211
Finally, unlike in a regular Shiny app, in an RMarkdown document's embedded Shiny apps you can't assume that relative paths from server.R will resolve correctly; that's because many apps can be running in the single session, including the RMarkdown document itself (which is also a Shiny app), so there's no way to make all of them happy.
For now, I recommend you load the data directly in the RMarkdown document and from the sub-apps just assume the data is already loaded--I believe this works, please correct me if I'm mistaken.
2018 update to this question:
Thanks to the bookdown package, knitr is now able to include HTML widgets, Shiny apps, and arbitrary websites using
knitr::included_url()
knitr::include_app()
Check out the document in the bookdown book for more examples:
https://bookdown.org/yihui/bookdown/web-pages-and-shiny-apps.html

Resources