I have a shiny app that I am building where the user selects a report from a radio button menu, and then the table displays on the page. I would like to add an option for the user to simultaneously view all reports. I have found something close to what I want from this thread https://gist.github.com/wch/5436415/ , but I can't quite seem to implement it properly. Basically, I think what I have to do is:
In the UI, make a call to uiOutput() to reactively update the User Interface. I will need multiple calls to htmlOutput() if the user selects the "all" button, but only one call to htmlOutput() if the use simply selects one report. For the record, I am creating my tables with the kable() function, which is why I call htmlOutput() instead of tableOutput().
In the server function, I need to make a call to renderUI() that provides the instructions on how many htmlOutput() calls there will be and which reports will be in each call.
Create a loop that then makes a call to renderText that then sends the html code for the htmlOutput function to interpret.
I can get most of the way there. I can get Shiny to have reactive tables, and output individual reports, but I am struggling to get the looping range to reactively update so that I see all three tables in my testing app. Here is what I have:
library(shiny)
library(shinydashboard)
library(knitr)
library(kableExtra)
data("cars")
data("iris")
data("airquality")
UI<-dashboardPage(
dashboardHeader(),
dashboardSidebar(sidebarMenu(
menuItem("Options", radioButtons(inputId = "Tables", label="test", choices= c("cars", "iris", "airquality", "all"))
) )),
dashboardBody(
uiOutput(outputId = "TABLE"),
textOutput("N")
)
)
server<-function(input, output){
TBL<-list("cars", "iris", "airquality")
T1<-knitr::kable(head(cars))
T2<-knitr::kable(head(iris))
T3<-knitr::kable(head(airquality))
tmp<-list(cars=T1, iris=T2, airquality=T3)
TABLES<-reactive({
ifelse(input$Tables=="all", tmp, tmp[input$Tables])
})
val<-reactive({
tmp<-TABLES()
length(tmp)})
n<-isolate(val())
output$TABLE<-renderUI({
req(input$Tables)
TAB<-TABLES()
TBL<-names(TAB)
tbls<-lapply(1:length(TBL), function(i){
tblnm<-paste("tbl", i, sep="_")
htmlOutput(tblnm)})
do.call(tagList, tbls)
})#Close Render UI
for(i in 1:n){
local({
j<-i
tblnm<-paste("tbl", j, sep="_")
output[[tblnm]]<-renderText(kables(TABLES()))
})
}
output$N<-renderText(n)
}#Close Server
shinyApp(ui = UI, server = server)
Here is where I think I am going wrong:
I included a textOutput() for the value of n, and despite having the reactive() call to get the length of TABLES, when I isolate() I still get the value of 1 even when I select the "all" report button, which should give me 3. Am I misinterpreting how isolate() works? Is there another way to get a value out of a reactive() function that can be used outside of a *Output() or reactive() function? Any guidance would be much appreciated. Thanks so much.
I think your server function is needlessly complex.
render functions are a reactive context themselves, so no need to define variables which only exist in those contexts as specifically reactive.
server<-function(input, output){
TBL<-list("cars", "iris", "airquality")
T1<-knitr::kable(head(cars))
T2<-knitr::kable(head(iris))
T3<-knitr::kable(head(airquality))
tmp<-list(cars=T1, iris=T2, airquality=T3)
output$TABLE<-renderUI({
if(input$Tables=="all"){ind <- names(tmp)}else{ind <- input$Tables}
lapply(tmp, HTML)[ind]
})
output$N <- renderText({
if(input$Tables=="all"){ind <- names(tmp)}else{ind <- input$Tables}
length(ind)
})
}
Related
I wrote a R script (MAIN.R) that converts PDF tables to CSV. When I run MAIN.R as an individual file, it functions well. I've tried it many times.
Currently, I'm working on a R shiny app that uses "MAIN.R" as a source and takes a pdf file as input. When I push the submit button, the output should appear in the MAIN panel. Unfortunately, the submit button does not function as intended.
May anyone please assist me with this, as I am new to Shiny?
UI.R
shinyUI(fluidPage(
titlePanel("DATASET CONVERSION"),
sidebarLayout(
fileInput("filein", label = h2("Select a file to convert.")),
submitButton("Submit")
),
mainPanel(
tableOutput("Dataset")
)
)
)
Server.R
source("MAIN.R")
shinyServer(function(input, output) {
outputdf <- reactive({ input$filein
})
output$Dataset <- renderTable({
outputdf()
})
})
Your Submit button is not currently linked to anything, so it will not do anything. If I am reading the code right, you are just taking the input dataset and storing it as the output of outputdf. Your output$Dataset then just picks up that outputdf and displays it as-is, without any work being done on it.
You use an action button like so:
## In UI.R
actionButton("execute", "Execute the Main Function")
## In Server.R
observeEvent(input$execute, {
## Do stuff here
})
Note that the actionButton has two parameters, inputID (which is how you refer to it) and text to display on top. For example, with input$filein, 'filein' is the inputID.
In Server.R, observeEvent won't do anything until it detects a change in input$execute, which happens when someone clicks the button. That is where you put your code to do stuff.
Now, in output$Dataset, you need to access the results of whatever you did in that observeEvent. One way to do that is to use a reactiveValue. This is just like a reactive, but instead of a function, it stores a data element. Initialize it as an empty dataframe, and then update it in the observeEvent. Something like this:
## In Server.R
treated_output <- reactiveValue(data.frame())
observeEvent(input$execute, {
## Run the function on the file
updated <- main_function(input$filein)
# Update your reactiveValue
treated_output(updated)
})
output$Dataset <- renderTable({
treated_output()
})
Does this make sense?
I'm trying to debug my Shiny app and would like to view a reactive dataframe with e.g. glimpse(df).
Initially I tried to create a breakpoint and then view the environment by my reactive df is a value not an object when used inside server.r. I also tried browser() but was not sure what it would do.
I did some searching on SO and tried various things using sink(), renderPrint() but had no success.
How can I print the contents of glimpse(some_reactive_df()) to the console when I run my app?
Calling print() from within the reactive({}) expression will do that.
library(shiny)
library(dplyr)
shinyApp(
ui <- fluidPage(
selectizeInput("cyl_select", "Choose ya mtcars$cyl ", choices = unique(mtcars$cyl)),
tableOutput("checker") # a needed output in ui.R, doesn't have to be table
),
server <- function(input, output) {
d <- reactive({
d <- dplyr::filter(mtcars, cyl %in% input$cyl_select)
print(glimpse(d)) # print from within
return(d)
})
output$checker <- renderTable({
glimpse(d()) # something that relies on the reactive, same thing here for simplicty
})
})
Assuming you provide Shiny a reason to run (and re-run) your reactive of interest, by having it be involved with a rendering in server() and linked output in ui(). This is usually the case for my debugging scenarios but it won't work unless the reactive is being used elsewhere in app.R.
Is there a possibility to reuse a dataTableOutput in several tabs? The only possibility I found was using a layout where the dataTableOutput gets its own row but I don't want it above all tabs.
If I just call the dataTableOutput multiple times, none of the tables get printed.
EDIT:
Thanks to the answer of daattali I got this almost done. The only thing I didn't mentioned before was, I need the two tables synchronised in a way. At the moment, when I try to update each other via proxy, the whole system gets buggy when selecting to many rows in a short time...
You can't use the same id (since you can't have two elements on the same page with the same id), but what you can do is generate the table once as a reactive value and then simply return that value inside the render table functions. This has the benefit of only running the code for generating the table once, and re-using the table in as many outputs as you want.
Example:
library(shiny)
ui <- fluidPage(
tabsetPanel(
tabPanel("tab1", "tab 1", DT::dataTableOutput("table1")),
tabPanel("tab2", "tab 2", DT::dataTableOutput("table2"))
)
)
server <- function(input, output, session) {
table_data <- reactive({
DT::datatable(iris)
})
output$table1 <- DT::renderDataTable(table_data())
output$table2 <- DT::renderDataTable(table_data())
}
shinyApp(ui = ui, server = server)
Note: After coming up with the answer I reworded the question to make if clearer.
Sometimes in a shiny app. I want to make use of a value selected by the user for a widget, as well as the previous value selected for that same widget. This could apply to reactive values derived from user input, where I want the old and the new value.
The problem is that if I try to save the value of a widget, then the variable containing that value has to be reactive or it will not update every time the widget changes. But, if I save the the value in a reactive context it will always give me the current value, not the previous one.
How can I save the previous value of a widget, but still have it update every time the user changes the widget?
Is there a way that does not require the use of an actionButton every time the user changes things? Avoiding an actionButton can be desirable with adding one is otherwise unnecessary and creates excess clicking for the user.
Seeing as the session flush event method seems to be broken for this purpose, here is an alternative way to do it using an observeEvent construct and a reactive variable.
library(shiny)
ui <- fluidPage(
h1("Memory"),
sidebarLayout(
sidebarPanel(
numericInput("val", "Next Value", 10)
),
mainPanel(
verbatimTextOutput("curval"),
verbatimTextOutput("lstval")
)
)
)
server <- function(input,output,session) {
rv <- reactiveValues(lstval=0,curval=0)
observeEvent(input$val, {rv$lstval <- rv$curval; rv$curval <- input$val})
curre <- reactive({req(input$val); input$val; rv$curval})
lstre <- reactive({req(input$val); input$val; rv$lstval})
output$curval <- renderPrint({sprintf("cur:%d",curre())})
output$lstval <- renderPrint({sprintf("lst:%d",lstre())})
}
options(shiny.reactlog = TRUE)
shinyApp(ui, server)
Yielding:
Update This answer was posted before the advent of the reactiveValues/observeEvent model in shiny. I think that #MikeWise 's answer is the better way to do this.
After some playing around this is what I came up with. The ui.r is nothing special
ui.r
library(shiny)
ui <- shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
selectizeInput(inputId="XX", label="Choose a letter",choices=letters[1:5])
),
mainPanel(
textOutput("Current"),
textOutput("old")
)
)
))
"Current" will display the current selection and "old" displays the previous selection.
In the server.r I made use of three key functions: reactiveValues, isolate and session$onFlush.
server.r
library(shiny)
server <- function(input, output,session) {
Values<-reactiveValues(old="Start")
session$onFlush(once=FALSE, function(){
isolate({ Values$old<-input$XX })
})
output$Current <- renderText({paste("Current:",input$XX)})
output$old <- renderText({ paste("Old:",Values$old) })
}
The server.r works like this.
First, Values$old is created using the reactiveValues function. I gave it the value "Start" to make it clear what was happening on load up.
Then I added a session$onFlush function. Note that I have session as an argument in my server function. This will run every time that shiny flushes the reactive system - such as when the selectizeInput is changed by the user. What is important is that it will run before input$XX gets a new value - so the value has changed at the selectizeInput but not at XX.
Inside the session$onFlush I then assign the outgoing value of XX to Values$old. This is done inside an isolate() as this will prevent any problems with input$XX gets updated with the new values. I can then use input$XX and Values$old in the renderText() functions.
I am new to Shiny and trying to build a more accessible input and output for a function I built. I am giving this to people that don't run R so trying to build something that runs my functions in the background and then spits out the answer.
I am having some trouble getting everything in the way that I want it unfortunately and dealing with a bunch of errors. However, here is my more pointed question:
The actual function that I want to run takes a name (in quotations as "Last,First") and a number.
PredH("Last,First",650)
So I want a shiny application that takes a name input and a number input that then runs this program and then spits back out a data table with my answer. So a couple of questions.
How do I get it in the right form to input into my equation on the server side script, do I need to return it in the function so it can be accessed using a function$table type access? (Right now I am just printing using cat() function in the console for the function but know that may not be usable for this type of application.
I want to return a dataframe that can be gotten at PredH14$table. How do I go about building that shiny?
Here is my code so far:
UI:
library(shiny)
shinyUI(pageWithSidebar(
# Application title
headerPanel("Miles Per Gallon"),
# Sidebar with controls to select the variable to plot against mpg
# and to specify whether outliers should be included
sidebarPanel(
textInput("playername", "Player Name (Last,First):", "Patch,Trevor"),
radioButtons("type", "Type:",
list("Pitcher" = "P",
"Hitter" = "H"
)),
numericInput("PAIP", "PA/IP:", 550),
submitButton("Run Comparables")
),
mainPanel(
textOutput("name")
)
Server:
library(shiny)
shinyServer(function(input, output) {
sliderValues <- reactive({
data.frame(
Name = c("name", "PA"),
Value = c(as.character(playername),
PAIP),
stringsAsFactors=FALSE)
})
name=input[1,2]
PAIP=input[2,2]
testing <- function(name,PAIP){
a=paste(name,PAIP)
return(a) }
output$name=renderText(testing$a)
})
I am not quite sure I understood your question 100% but I clearly see you are wondering how to pass the input of the UI into the server and maybe, the other way back.
In your server code, clearly you are not getting any input from the UI. Basically you have created three input variables in your ui.R:
1. input$playername
2. input$type
3. input$PAIP
And one output:
1. output$name
Just let you know, the function sliderValues <- reactive(..) is called every time there is any input from the input... like people click the dropdown list or people modifies words in the text box.
You can even get started without the submit button just to get started. But the existence of the submit button actually makes everything easier. Create a submit button for an input form. Forms that include a submit button do not automatically update their outputs when inputs change, rather they wait until the user explicitly clicks the submit button.
So you can put your code in a way similar like this:
# server.R
library(shiny)
shinyServer(function(input, output) {
sliderValues <- reactive({
result <- ... input$playername ... input$type ... input$PAIP
return(result)
})
output$name <- renderPlot/renderText (... sliderValues...)
})
# ui.R
library(shiny)
shinyUI(pageWithSidebar(
headerPanel("Miles Per Gallon"),
sidebarPanel(
textInput("playername" ... ),
radioButtons("type" ... ),
numericInput("PAIP" ... ),
submitButton("...")
),
mainPanel(
textOutput/plotOutput...("name")
)
))
In the end, check out the shiny example that might be what you want.
library(shiny)
runExample('07_widgets')