I am currently building an application with shinydashboard and googleVis. gvisTable is in my opinion the best way to show my outputs. My problem is the following:
The application (and thus, googleVis) works perfectly with the R browser on my computer, but if I want to show the application on an other computer, the application starts and computes everything asked but the tables are not rendering with gvisTable.
Since it works on my computer, I don't think the problem comes from the code, but I show you the used packages and an example of how I use gvisTable.
I use the following packages:
library(shiny)
library(shinydashboard)
library(shinyBS)
library(shinyjs)
library(texreg)
library(googleVis)
In the file server.R, when I want to output a table I use code like
output$coefftable <- renderGvis({
ConfInv <- 0.05
model <- Arima_Model()
CoeffTable <- CoefficientsFunction(ConfInv,model)
gvisTable(CoeffTable,options(digits=4))
})
where the function CoefficientsFunction returns a table using data.frame.
For the output, I use in ui.R
htmlOutput("coefftable")
I don't understand where the problem comes from, it might be from the RStudio browser as suggested in gvisTables not rendering in Shiny apps.
Do you think I might use an other browser? If yes, which one would be the best?
Try assigning your table and then return it inside server.R like this:
output$coefftable <- renderGvis({
ConfInv <- 0.05
model <- Arima_Model()
CoeffTable <- CoefficientsFunction(ConfInv,model)
table <- gvisTable(CoeffTable,options(digits=4))
return(table)
})
Related
I webscraped 2 tables (A and B). Then I merge them by rows (rbind). When I launch it, everything is ok. When I wanna use it in shiny app there is something wrong. Below structure of tables and what shiny shows. Any suggestion? Where could be the problem? Unfortunatelly, I can not show the code, because this is for my thesis. I would be very grateful for your help.
As you can see the problem is with third column. B table has all rows with NA. After merge, all data from A table has also NA.
In shiny table is showed by renderTable.
Structure of tables A and B
I have no answer for your question, but I would like to write something and there is not enough space for this in comment section, so I will write this as answer and eventually delete later. So - I rather believe that there is something wrong with your code which you use inside shiny and would like to check this with your help. I assume you need some help with debugging, so I will post a code below:
library(shiny)
ui <- fluidPage(
tableOutput("table")
)
server <- function(input, output, session) {
my_df <- reactive({
data.frame(a = c(1, 2, 3),
b = c(4, 5, 6))
})
output$table <- renderTable({
my_df()
browser()
})
}
shinyApp(ui, server)
In the code above I have made one output (table output) and - on the server side in reactive - I'm creating data.frame. Then I use this reactive function inside my output (output$plot). However, the last line inside output$plot is function browser() which is used for debugging. You can try my code in your console and see that when you run shiny app, it immediately moving back to console (but this is "dubugging state", so console looks a little different, for example there is a button "stop" with red square which can be use to close debugging state). Please run my shiny app and when you will be back in the console, in the debugging state, type my_df() to see the data.frame object. Could you please do the same with your shiny app? I mean, could you use browser() function on the last line in your renderTable? And come back and tell if the last column contains only NA or not when displayed in the console? If not, then I would say that you are doing something different in Shiny than manually with your tables.
Introduction
I have created an R shiny dashboard app that is quickly getting quite complex. I have over 1300 lines of code all sitting in app.R and it works. I'm using RStudio.
My application has a sidebar and tabs and rather than using modules I dynamically grab the siderbar and tab IDs to generate a unique identifier when plotting graphs etc.
I'm trying to reorganise it to be more manageable and split it into tasks for other programmers but I'm running into errors.
Working Code
My original code has a number of library statements and sets the working directory to the code location.
rm(list = ls())
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
getwd()
I then have a range of functions that sit outside the ui/server functions so are only loaded once (not reactive). These are all called from within the server by setting the reactive values and calling the functions from within something like a renderPlot. Some of them are nested, so a function in server calls a function just in regular app.R which in turn calls another one. Eg.
# Start of month calculation
som <- function(x) {
toReturn <- as.Date(format(x, "%Y-%m-01"))
return(toReturn)
}
start_fc <- function(){
fc_start_date <- som(today())
return(fc_start_date)
}
then in server something like this (code incomplete)
server <- function(input, output, session) {
RV <- reactiveValues()
observe({
RV$selection <- input[[input$sidebar]]
# cat("Selected:",RV$selection,"\r")
})
.......
cat(paste0("modelType: ",input[[paste0(RV$selection,"-modeltype")]]," \n"))
vline1 <- decimal_date(start_pred(input[[paste0(RV$selection,"-modeltype")]],input[[paste0(RV$selection,"-modelrange")]][1]))
vline2 <- decimal_date(start_fc())
.......
Problem Code
So now when I take all my functions and put them into different .R files I get errors indicating the functions haven't been loaded. If I load the source files by highlighting them and Alt-Enter running them so they are loaded into memory then click on Run App the code works. But if I rely on Run App to load those source files, and the functions within them, the functions can't be found.
source('./functionsGeneral.R')
source('./functionsQuote.R')
source('./functionsNewBusiness.R')
source('./ui.R')
source('./server.R')
shinyApp(ui, server)
where ui.R is
source('./header.R')
source('./sidebar.R')
source('./body.R')
source('./functionsUI.R')
ui <- dashboardPage(
header,
sidebar,
body
)
Finally the questions
In what order does R Shiny Dashboard run the code. Why does it fail when I put the exact same inline code into another file and reference it with source('./functions.R')? Does it not load into memory during a shiny app session? What am I missing?
Any help on this would be greatly appreciated.
Thanks,
Travis
Ok I've discovered the easiest way is to create a subfolder called R and to place the preload code into that folder. From shiny version 1.5 all this code in the R folder is loaded first automatically.
I am totally new to Shiny, so first, apologize my inexperience.
I am writing a dynamic report using R Markdown, and I have several plots that deserve being shown dynamically.
Let's work with the mtcars dataset, and let's create 4 plots:
plot1 <- plot(mtcars$mpg)
plot2 <- plot(mtcars$cyl)
plot3 <- plot(mtcars$hp)
plot4 <- plot(mtcars$qsec)
So, how can I create a dropdown menu with these four plots being displayed accordingly?
I mean your example is the simplest shiny example I have ever seen on stackoverflow. I suggest you take a bit of time doing the tutorial, then you try building your own app and if you're stuck come back here :)
To learn shiny I recommend Rstudio's tutorial. After learning and forgetting everything again I advise you to use the wonderful cheatsheet provided by Rstudio.
The app.r looks like this:
library(shiny)
library(plotly)
### ui.r
ui <- fluidPage(selectInput('my_dropdown','Choose Column',colnames(mtcars)),
plotOutput('my_plot')
)
### server.r
server <- function(input, output) {
output$my_plot <- renderPlot(
plot(mtcars[,input$my_dropdown],ylab=input$my_dropdown,xlab='value')
)
}
shinyApp(ui,server)
Just for the sake of completeness. This kind of graph could be created using plotly as well. The advantage is that you can use this in a standalone html. The disadvantage is that dropdowns with plotly are quite code-intensive. The tutorial for plotly is here: https://plot.ly/r/dropdowns/
There are resources on how to create a Minimal, Complete, and Verifiable example in general on Stack Overflow, and on how to make a great R reproducible example. However, there are no similar guidelines for shiny questions, while adhering to certain standards makes it much more likely that quality answers will be given, and thus that your question will be resolved.
However, asking a good Shiny question can be difficult. shiny apps are often large and complex, use multiple data sources, and the code is often split over multiple files, making it difficult to share easily reproducible code with others. Even though a problem may be caused in server.R, the example is not reproducible without the contents of ui.R (and possibly other files like stylesheets or global.R). Copy-pasting the contents of all these files individually is cumbersome, and requires other users to recreate the same file structure to be able to reproduce the problem.
So; how to convert your shiny app into a good reproducible example?
Example data
Of course, all guidelines regarding sample data mentioned in the answer on the question “how to make a great R reproducible example” also hold when creating questions related to Shiny. To summarize: Make sure no additional files are needed to run your code. Use sample datasets like mtcars, or create some sample data with data.frame(). If your data is very complex and that complexity is really required to illustrate the issue, you could also use dput(). Avoid using functions like read.csv(), unless of course you have questions related to functions like fileInput.
Example code
Always reduce your code to the bare minimum to reproduce your error or unexpected behavior. This includes removing calls to additional .CSS files and .js files and removing unnecessary functions in the ui and the server.
Shiny apps often consist of two or three files (ui.R, server.R and possibly global.R), for example this demo application. However, it is preferable to post your code as a single script, so it can easily be run by others without having to manually create those files. This can easily be done by:
wrapping your ui with ui <- fluidPage(…),
the server with server <- function(input,output, session) {…},
and subsequently calling shinyApp(ui, server).
So a simple skeleton to start with could look as follows:
library(shiny)
ui <- fluidPage(
)
server <- function(input,output,session) {
}
shinyApp(ui, server)
Working Example
So, taking all the above into account, a good Minimal, Complete, and Verifiable example for a Shiny application could look as follows:
library(shiny)
df <- data.frame(id = letters[1:10], value = seq(1,10))
ui <- fluidPage(
sliderInput('nrow', 'Number of rows', min = 1, max = 10, value = 5),
dataTableOutput('my_table')
)
server <- function(input, output, session) {
output$my_table <- renderDataTable({
df[1:input$nrow,]
})
}
shinyApp(ui, server)
Adding CSS
There are multiple ways to add custom CSS to a Shiny application, as explained here. The preferred way to add CSS to a Shiny application in a reproducible example is to add the CSS in the code, rather than in a separate file. This can be done by adding a line in the ui of an application, for example as follows:
tags$head(tags$style(HTML('body {background-color: lightblue;}'))),
I am trying to write a shiny app that loads several data frames. The data frames for my plots all work very well, but one data.frame which I want to use as a list of options in a dropdown menu does not load. If I load the frame seperately in the R session, everything works, but if I only run the shiny app, the selectors won't update.
library(shiny)
ui <- fluidPage(
#...
selectInput("mats", "Text",
selectors)
# ...
)
server <- function(input, output){
# ...
df1=read.csv("./data/file.csv", sep=";", head=T, stringsAsFactors = F)
df1$choices=as.character(df1$choices)
selectors=c("All", df1$choices)
#...
}
shinyApp(ui = ui, server = server)
I think, I need the selectors in the server function, so I loaded the data frame there together with my other data frames. Is that the right place and what do I need to do to get this running?
Best
There is a number of problems with your code:
Following the documentation, choices in selectInput should be a list.
If you want to create an element that would be available across the ui and server please consider reading the linked article on scoping rules in Shiny and defining your object in global.R.
With respect to the 1st point, if your intention is to use a data.frame column as a base for menu selection, you can apply the following transformation:
my_new_list <- split(df$id, df$subject)
as provided in this answer by #user3710546 to a similar question that I've asked in past.
Side note
Please consider having a look at the discussion on making a reproducible example in R. If you care to redo your example using some publicly available data, it will be easy to produce a solution. If I understood the problem correctly, you want to use data.frame column as a base for UI element, which is not difficult on its own.
.