Embedding Shiny app in knitr document - r

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

Related

How to use a shiny app inside rmarkdown file?

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.

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 ?

How do I assign the working directory for rmarkdown/knitr interactive doc on shinyApps.io?

I have a fully functional interactive shiny doc using knitr/r markdwon.
However, when I try to publish (deploy) it to shinyApps.io, I get an error saying the .PNG file I try to incorporate into the doc (using readPNG from the png package) is unable to open.
I know the problem is related to working directories.
In my original code I assigned a working directory to my folder (i.e., "C:/Users/NAME/documents/...." that contains both my .rmd file and my .png file. However, obviously my folder doesn't exist on the shinyapps.io.
So how exactly do I set my working directory to open the .png file via my doc on shinyapps.io?
I can't find anywhere that explicitly walks through this process. Please help explain this simply/basically for me.
Example:
Assume I have a folder in "C:/Users/NAME/documents/Shiny" that contains 2 files: "shiny.rmd" and "pic.png". I want "pic.png" to be rendered in my shiny.rmd doc.
Currently I have:
---
title: "TroubleShoot"
output: html_document
runtime: shiny
---
```{r ,echo=FALSE,eval=TRUE}
library(png)
library(grid)
direct <- "C:/Users/NAME/documents/Shiny/"
img <- readPNG(paste0(direct,"pic.PNG"))
grid.raster(img)
```
How do I rewrite my code so it works on shinyApps.io?
Do I need to create and name folders in specific ways to place my 2 files into before deploying?
When you paste the c drive to direct, and read the direct into img, you are sending the app/markdown to your local drive. You need to use a relative path to the project. I would suggest something like:
direct <- "./"
Which uses the relative path, not the absolute path.
That said you might be able to skip that step entirely if the .png is in the same folder as the shiny object. just call the file name and format and leave it as that.
Also, check you use of ". Your syntax highlighting indicates your code won't run properly as it thinks some of your functions and variables are character strings because you've misplaced your quotes around read.png(). That's probably just a copy and paste typo though.
In summary, call the image via grid.raster("./pic.PNG"), and brush up on how working directories and relative paths work.
In the absence of knowing exactly how you're 'setting' your working directory:
In rStudio to correct and easiest approach is to make a 'New Project' for every New Project. You can do this as the first step in your project, or you can add a project file to an existing directory.
When you do this it automatically sets your working directory correctly. The way you seem to be doing it is not correct, you are merely supplying a 'path'. If you were to not want to use a project for some reason (I can't think of a case where that would be right), then you can always use setwd(), however, I believe this needs to be used in every session. A true project doesn't have that requirement.
This will then allow you to deploy your app properly as it will update the working directory to the one on the host machine at shinyapps.io when it is initialised there.
Finally, using the correct relative syntax "./path/to/my.file" to reference all your assets, images, data etc, should correct your issue as stated in the question.

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.

Resources