My uiOutput is not showing properly in Shiny App - r

I pretend to upload an excel file and get to choose between the sheets of that file. It is working perfectly but for some reason the name of the sheets is not taking up the whole space and doing this weird thing:
Wrong display of name of sheets
The part of the script where I establish it is:
...
sidebarLayout(
sidebarPanel(
column(4, fileInput("file2", "Select file (.xls/.xlsx)",
accept = c(".xls",".xlsx")
)),
column(8, uiOutput("name_of_my_sheets", style='padding:6px; font-size:80%; position:relative')),
I tried many things like columning and positioning it differently but can´t get it to work. When I use half of my screen to test de app, it works well.
Right display of name of sheets
I cannot post the whole code for confidential issues unluckily but be happily prone to answer any questions. Thank you in advance!!

Related

Display locally-stored image in R Shiny

I spent a fair amount of time trying to solve that issue.
Of course I did my homework before sharing my issue here.
In particular I have unsuccessfully consulted :
local image in shiny app without img(src())?
Shiny can not display Image locally
adding local image with html to a Shiny app
R Shiny img() on UI side does not render the image
Display images from web in shiny R
Image failing to display in R shiny
Embedding Image in Shiny App
How to place an image in an R Shiny title
So I did create a 'www' folder at the root of the RStudio project file where I put some pictures.
These pictures are used in the titlePanel but also by the main htmlwidget the application calls.
It is crucial for me to have these pictures stored locally because the application may be running in a secured environment without any access to the Internet.
I tried a relative path to these pictures and an absolute path: no picture was displayed.
Then I noticed some kind of inconsistency: I experience this issue only when I run the application through the regular command in RStudio, "Run Selected Line(s)".
On the other hand, when I run the application through the dedicated command "Run App" (in the top right corner in RStudio, green arrow), I don't have this issue anymore, the pictures display nicely (but the input data are somehow inspected and it takes a lot of time before the application is launched).
Initially I thought that displaying local images would be much easier than with remote images stored on the Internet but it seems it is rather the other way around.
Hence my questions:
Do you know why we can observe this difference (which is an inconsistency to me)?
And do you know how I could still continue to use the regular execution command ("Run Selected Line(s)")?
Best regards,
Olivier
For me the following also works when running the app via Run Selected Line(s) in RStudio:
library(shiny)
# create some local images
if(!dir.exists("myimages")){
dir.create("myimages")
}
myPlotPaths <- paste0("myimages/myplot", seq_len(3), ".png")
for (myPlot in myPlotPaths) {
png(file = myPlot, bg = "transparent")
plot(runif(10))
dev.off()
}
myImgResources <- paste0("imgResources/myplot", seq_len(3), ".png")
# Add directory of static resources to Shiny's web server
addResourcePath(prefix = "imgResources", directoryPath = "myimages")
ui <- fluidPage(
tags$img(src = myImgResources[1], width = "400px", height = "400px"),
tags$img(src = myImgResources[2], width = "400px", height = "400px"),
tags$img(src = myImgResources[3], width = "400px", height = "400px")
)
server <- function(input, output, session) {
}
shinyApp(ui, server)
Managing directories can be tricky.
You could use the here package to make things much easier to handle directories in R projects, see Ode to the here package.
After opening the project, images in www can then easily be accessed by:
here::here('www/myimage.jpg')
This will also work for sourcing an app or a script.
I don't have a specific answer, but Hadley has showed an example of how to display images from your stored locally under the 'Graphics' Chapter in 'Mastering shiny' book. The book is under development and it should be released soon, I will paste the link for that chapter:
Graphics chapter
The example is under images section.
HTH

R Shiny - cache big dataframe

I'm quite new to Shiny, so my apologizes if my question is an easy one. I tried to check on google and stackoverflow but couldn't locate a simple and helpful answer so far.
What's my goal/issue: I'm coding a Shiny page that displays a table with hundreds of thousands of rows.
Data is sourced from different databases, manipulated, cleaned, and displayed to all the users upon request.
Problem 1: in order to load all the data, the script takes almost 5minutes
Problem 2: if at 8:00am user1 requests this data and at 8:05am user2 requests the same data, two different queries are launched and also two different spaces in memory are used to show exactly the same data to two different users.
So the question is: shall I use a cache system to enhance this process?
if not, what else shall I use?
I found a lot of official Shiny documentation on caching plots but nothing related to caching data (and I found this quite surprising).
Other useful information: data in cache should be deleted every evening around 10pm since new data will be available the next day / early morning.
Code:
ui <- dashboardPage( # https://rstudio.github.io/shinydashboard/structure.html
title = "Dashboard",
dashboardHeader(title = "Angelo's Board"),
dashboardSidebar( # inside here everything that is displayed on the left hand side
includeCSS("www/styles.css"),
sidebarMenu(
menuItem('menu 1', tabName = "menu1", icon = icon("th"),
menuItem('Data 1', tabName = 'tab_data1'))
)),
dashboardBody(
tabItems(
tabItem(tabName = 'tab_data1')),
h3("Page with big table"),
fluidRow(dataTableOutput("main_table"))
))
server <- function(input, output, session) {
output$main_tabl <- renderDataTable({
df <- data.frame(names = c("Mark","George","Mary"), age = c(30,40,35))
})
}
cat("\nLaunching 'shinyApp' ....")
shinyApp(ui, server)
Resources I used to check for potential solution:
How to cache data in shiny server? but apparently I cannot use Jason Bryer package
https://shiny.rstudio.com/reference/shiny/1.2.0/memoryCache.html but I have no idea of how to use this code applied to my example
https://shiny.rstudio.com/articles/plot-caching.html is mainly focused on plot caching
Any help would be much appreciated. Thanks
I would break out the bulk of your ETL processes into a separate R script and set that script to run on a cron. You can then have this script write out the processed dataframe(s) to a .feather file. Then have your shiny app load the feather file(s) - feather is optimized for reading so should be fast.
Example, take the necessary libraries and code out of your server.R (or app.R) file, and create a new R script called query.R. That script performs all the ETL operations and finally writes out your data to a .feather file (requires the feather package). Then create a crontab to run that script as often as needed.
Your server.R script then just needs to read in that feather file when the app loads and you should see a significant performance improvement. In addition, you have have the query.R script run during off hours so that performance on the linux box isn't negatively impacted.
Another option, put this DataFrame in global.R and change /etc/shiny-server/shiny-server.conf by adding «app_idle_timeout 0» after «location / {». This will disable application idle timeouts in Shiny Server, so global.R will be in RAM for all users.
To prevent first user from long data loading, you can put in cron «#reboot wget -O index.html localhost:3838» on your server, so on every reboot global.R will load to memory automatically.
Also, about pre-cache organisation you can read here.

Is shiny able to use interactive ui?

I'm almost done with my project and I'm trying to do some aesthetic changes to my app in order to be more user friendly and attractive.
The idea:
Since my app requires to upload a table in order to work, I thought it would be better if I put a stand alone large upload button in the middle of the screen and then a navigation bar would appear with the results, plots, downloads would appear.
Here's what I've tried:
shinyUI(
fileInput("file","Upload the file")
if(!is.null(input$file)) {
navbarPage("My Application",
tabPanel("Data", tableOutput("table")),
tabPanel("Summary", tableOutput("sum")),
tabPanel("Regression", verbatimTextOutput("reg")),
tabPanel("Wavelet Coefficients", htmlOutput("tmod1"),
tableOutput("mod1"),
tableOutput("mod2")),
tabPanel("Wavelet Plot", plotOutput("plot")),
tabPanel("About file", tableOutput("filedf"))
)}
)
The error is the following:
ERROR: D:\OneDrive\MODWT App/ui.R:7:1: unexpected 'if'
6:
7: if
^
Is there any solution to this? :/
My current "plan b" is to create two apps, where the first is the upload one, and if the user upload the file then server.R will call the "original" app. Is this even possible?
I apologise if this question seems silly but I'm a noob coder, so I'm not aware of the limitations.
Thanks
To dynamically add or remove UI elements in Shiny you should use the built-in dynamic UI functions such as conditionalPanel.
You'll move the logic from your if statement to the condition argument of conditionalPanel.
There are a few other functions like that which you can read about here and you can also use custom JS.

R shiny uploading a pdf from local drive does not work

I am trying to upload a pdf to shiny. If the pdf file is from the Internet, the following code works well:
library(shiny)
runApp(list(
ui = fluidPage(
sidebarLayout(
sidebarPanel(
h5("use case - embed a pdf user guide in the app - embed as a local pdf or from web URL")
),
mainPanel(
tabsetPanel(
# using iframe along with tags() within tab to display pdf with scroll, height and width could be adjusted
tabPanel("Reference",
tags$iframe(style="height:800px; width:100%; scrolling=yes",
src="https://cran.r-project.org/doc/manuals/r-release/R-intro.pdf")),
tabPanel("Summary"),
tabPanel("Plot")
)
))
),
server = function(input, output,session){}
))
However, when I tried to upload a pdf saved in Desktop, which is also the working directory, I cannot see the pdf file. I used src="example.pdf" to replaced the web file link. As suggested by some other StackOverflow posts, I saved the pdf file in a folder named www, but it still not working.
The system is MacOS X El Capiton and safari browser. I am not sure if that makes any difference.
Thanks a lot!
You have two options. The first one: just put your file example.pdf on a /www directory where your app file is. The second: use the addResourcePath function before running your app to make a local directory accessible.
addResourcePath("pdfs", "c:/temp/mypdfs")
later use it as
src="pdfs/example.pdf"

R Shiny app progress Indicator for loading data

Shiny is our internal BI tool. For our Shiny apps, we load data before shinyServer running:
load("afterProcessedData.RData")
# or dt = fread("afterProcessedData.csv")
shinyServer(function(input, output, session){ ...
However, some of apps are loading big files and they take up to 30s to load up. Many users, when they open a page, don't know whether the page is broken since it is stuck when it is loading. They may close it or click filters, which may cause an error. In this case, a progress bar will be very helpful. I notice withProgress() may help but it has to be inside reactive() or renderXx().
One way I can do is to have laod() warpped with reactive() inside the shinyServer(function(input, output, session){ but my concern is it will slower the performance. And my users very care about the responsive performance.
Any suggestions for this situation?
Edit: I guess there is not an easy way to do this. I have another thought. Maybe I can show a text on the screen saying 'the data is loading', but I have to make it disappear after the first table gets show up. However, I don't know how to set up the condition. Below is my code showing first table:
dashboardBody(
fluidRow(
tabBox(width = 12,
tabPanel("Summary",
dataTableOutput("data1")),
Thank you in advance!
Even though I am still interested in knowing how to add process bar for load(), I have implemented the alternative solution, which is good for now. It has a text saying 'the data is loading...' on the page, and it will disappear after first table shows up.
#server.R firstData is a reactive function to get the data for 1st table
output$firstTable = reactive({
return(is.null(firstData()))
})
#ui.R
conditionalPanel(
condition = "output.firstTable",
box(width = 12,
h1("The data is loading...")
)
)
To reference the intriguing note from #user5249203 , withSpinner() looks to be a useful option for this functionality and is a part of the shinycssloaders package. I have not used myself, but it is definitely an intriguing package that happens to be on CRAN and to have some nice examples: https://andrewsali.shinyapps.io/example/

Resources