I added the button but the values will automatically change before I hit "Update Order", I don't know how to fix it. Should be like this:enter image description hereBelow is my code:
library(shiny)
ui <- fluidPage(
titlePanel("My Simple App"),
sidebarLayout(
sidebarPanel(
helpText("Controls for my app"),
selectInput("fruitchoice",
label = "Choose a fruit",
choices = list("Apples",
"Oranges",
"Mangos",
"Pomegranate"),
selected = "Percent White"),
sliderInput("amt",
label = "Order Amount:",
min=0, max = 100, value=20),
actionButton ("Update","Update Order")
),
mainPanel(
helpText("Fruit Chosen:"),
verbatimTextOutput("fruit"),
helpText("Order Amount"),
verbatimTextOutput("amt")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
SelectInput <- eventReactive (input$Update , {
runif(input$fruitchoice,amt)
})
output$fruit = renderText(input$fruitchoice)
output$amt = renderText(input$amt)
}
# Run the application
shinyApp(ui = ui, server = server)
I will show you, how to rewrite your code to get this update behavior, however I would like to also get you know that this part of code:
SelectInput <- eventReactive (input$Update , {
runif(input$fruitchoice,amt)
})
Is wrong for three reasons: (1) object amt do not exists, you probably want input$amt; (2) even if you change amt to input$amt code won't work and you will get error; (3) now you are not using SelectInput in any place in your application, so there is no reason for this part to exists, however as I don't know what is your aim and how will look the final app, I'm not saying this is generally wrong.
Ok, so now about this update button. We will focus on this code:
output$fruit = renderText(input$fruitchoice)
output$amt = renderText(input$amt)
Here you instruct program to (re)render text when input$fruitchoice or (in second line) when input$amt change, but you want to (re)render text only when user clicks the button, so you need two things - first, be sure that user clicked the button and do not (re)render text when one of input$ changes. This will work:
output$fruit = renderText({
req(input$Update)
isolate(input$fruitchoice)
})
output$amt = renderText({
req(input$Update)
isolate(input$amt)
})
If I understand Shiny correctly, isolate() makes sure that text is not (re)rendering when input$ changes (however it has internally the new values) and req() makes sure that the input$Update was clicked; and when is clicked again, Shiny recomputes [(re)renders] text. It recomputes, because we didn't use isolate() on input$Update I think.
There's a few things wrong in your code. I will give a bit of explanation for each one:
You are initializing with reactive inputs. By using renderText(input$...) you create a text output that updates automatically when your input updates. Automatically is the problem here, you don't want that. We are going to write an alternative method that stores the inputs in a separate variable that we only allow to be updated when the button is pressed. We initialize that variable like so:
rv <- reactiveValues(fruit = "Apples",
amt = 20)
EventReactive creates a reactive variable that can later be used in the code. Generally speaking what you want to use in these kind of scenarios is observeEvent. You can do so like this:
observeEvent (input$Update , {
rv$fruit <- input$fruitchoice
rv$amt <- input$amt
})
We now have a list of variables under the name "rv" and an observeEvent that updates this variable every time the button gets pressed. All that is left to do is create the renderText which you can do like so:
output$fruit <- renderText(rv$fruit)
output$amt <- renderText(rv$amt)
Related
Question
In R Shiny, when using
renderUI
uiOutput
to dynamically generate sets of controls, such as:
checkboxes
radiobuttons
text boxes
how can I harvest those values or populate input by causing events?
As-is, those generated controls appear to be "display only". Making a selection, marking a checkbox, or entering data only updates the display, but no Event is created and the values are not populated into the "input" variable ( ReactiveValues ); thus, nothing is received by the Shiny server process.
If these control inputs are in-fact isolated, it completely undermines the point of dynamically creating controls.
Obviously, I'm hoping that this issue has been addressed, but my searches haven't turned it up.
In my specific case, the UI allows the user to:
Select and upload a CSV file.
The logic identifies numerical, date, and grouping columns, and produces 3 sets of radiobutton control sets. The idea is that you pick which columns you are interested in.
Picking a grouping column SHOULD return that columnID back to the server, where it will display a discrete list of groups from which to select. This fails, as the selections do not generate an Event, and the input variable (provided to server.R) only contains the ReactiveValues from the static controls.
That said, the display of the controls looks fine.
Step#0 screenshot:
Step#1 screenshot:
On the server.R side, I'm using code as below to create the radioButtons.
output$radioChoices <- reactive({
...
inputGroup <- renderUI({
input_list <- tagList(
radioButtons(inputId = "choiceGrp", label = "Available Grouping Columns", choices = grpColumnNames, inline = TRUE, selected = selectedGrp),
radioButtons(inputId = "choiceNumb",label = "Available Numerical Columns",choices = numColumnNames, inline = TRUE, selected = selectedNum),
radioButtons(inputId = "choiceDate",label = "Available Date Columns", choices = dateColumnNames, inline = TRUE, selected = selectedDate),
hr()
)
do.call(tagList, input_list)
})
print(inputGroup)
output$radioChoices <- inputGroup
})
I have played around with a Submit button and ActionButtons to try and force an Event, but no dice. My skull-storming is now going to places like "do I need to somehow use Javascript here?"
Many thanks to all of you who are lending me your cycles on this matter.
I'm not sure I understand your problem. Here's a MWE that accesses the value of a widget created by uiOutput/renderUI. The values of widgets created by uiOutput/renderUIcan be accessed just like those of any other widget.
If this doesn't give you what you want, please provide more details.
library(shiny)
ui <-
fluidPage(
uiOutput("dataInput"),
textOutput("result")
)
server <- function(input, output, session) {
output$dataInput <- renderUI({
selectInput("beatles", "Who's your favourite Beatle?", choices=c("- Select one -"="", "John", "Paul", "George", "Ringo"))
})
output$result <- renderText({
req(input$beatles)
paste0("You chose ", input$beatles)
})
}
shinyApp(ui, server)
I am relatively new to shiny app and is trying to make a simple app : while i am able to run ui.R correctly, i am having problem with server.R......what i want is to take a value of slider bar "post" (this number will be used as arg. of function "wbpg"),select the type of plot from dropdown menu and plot the corresponding variable when action button "RUN" is pushed.....all the results and plots are saved when a function named "wbpg(x)" (where "x" is the value of slider bar)...when wbpg(x) is run it returns plots(this contains list of all the plots in drop down menu)
#UI.R
shinyUI( fluidPage(
titlePanel(title=h4("Text Mining on thread",align="centre")),
sidebarLayout(
sidebarPanel(
sliderInput("post","1. Choose no. of posts you want to run the model",value = 1, min = 1, max = 30000),
br(),
selectInput("plotvar","2. Select the variable you want to plot",choices=c("raw_dat"=1,"content"=2,"barplot"=3,"genderplot"=4,"girlplot"=5,"rawplot"=6,"adjplot"=7,
"drinkplot"=8,"damageplot"=9,"songplot"=10,"sentimentplot"=11)),
br(),
actionButton(inputId="act",label = "RUN!")
),
mainPanel(
textOutput("out"),
#tableOutput("tab"),
plotOutput("hist1")
)
)
))
this is server file, where the problem exists:
#server.R
shinyServer(function(input, output) {
#observeEvent(input$action,wbpage(as.numeric(input$post)))
#output$data<-renderPrint({str(get(content))})
observeEvent(input$act,{wbpg(np)})
output$out<-renderText(paste("No. of posts mined: ",input$post))
#defaul<-reactiveValues(data=wbpage(3000))
np<-wbpage(as.numeric(input$post))
output$hist1 <- renderPlot({barplot})
})
#output$hist1 <-
#renderPlot({
#plots$barplot
#output$tab<-
# renderTable({
# head(data())
#})
#output$hist2 <- renderPlot({
#hist(rnorm(input$num))
#raunchyplot
#})
#})
Without having access to your function (wbpg), let me try to help you with the values returned from the 'observeEvent' call. I think your problem is the placement of the '})' on the line with 'observeEvent'. Everything you want to happen upon clicking the 'Run' button needs to be within the '})'. If this isn't what you need, please restate the question.
In place of your 'observeEvent' command, use the following code to see the data returned every time you click on the 'Run' button. It shows the value of the slider bar and the number from the drop down menu.
observeEvent(input$act,{
print (paste(input$post,input$plotvar,sep=' '))
})
Description
I have a textAreaInput box that I want to start with a default value. The user can click 2 actionButtons (Submit & Random Comment). Submit updates the comment from the textAreaInput for further processing (plot, etc.) while Random Comment sends a new random value to textAreaInput (the user may type in the textAreaInput box as well). I almost have it but can't get the app to update textAreaInput's value until the Submit button is pressed.
Question
I want it to be updated when Random Comment is pressed but still allow the user to erase the text box and type their own text. How can I make the app do this?
MWE
library(shiny)
library(shinyjs)
library(stringi)
shinyApp(
ui = fluidPage(
column(2,
uiOutput("randcomment"),
br(),
div(
actionButton("randtext", "Random Comment", icon = icon("quote-right")),
div(actionButton("submit", "Submit", icon = icon("refresh")), style="float:right")
)
),
column(4, div(verbatimTextOutput("commenttext"), style = 'margin-top: 2cm;'))
),
server = function(input, output) {
output$randcomment <- renderUI({
commentUi()
})
comment_value <- reactiveValues(default = 0)
observeEvent(input$submit,{
comment_value$default <- input$randtext
})
renderText(input$randtext)
commentUi <- reactive({
if (comment_value$default == 0) {
com <- stri_rand_lipsum(1)
} else {
com <- stri_rand_lipsum(1)
}
textAreaInput("comment", label = h3("Enter Course Comment"),
value = com, height = '300px', width = '300px')
})
output$commenttext <- renderText({ input$comment })
}
)
I'd approach this a little bit differently. I would use reactiveValues to populate both of the fields, and then use two observeEvents to control the contents of the reactiveValues.
I don't think you need a reactive at all in this situation. reactive is good when you want immediate processing. If you want to maintain control over when the value is processed, use reactiveValues.
library(shiny)
library(shinyjs)
library(stringi)
shinyApp(
ui = fluidPage(
column(2,
uiOutput("randcomment"),
br(),
div(
actionButton("randtext", "Random Comment", icon = icon("quote-right")),
div(actionButton("submit", "Submit", icon = icon("refresh")), style="float:right")
)
),
column(4, div(verbatimTextOutput("commenttext"), style = 'margin-top: 2cm;'))
),
server = function(input, output) {
# Reactive lists -------------------------------------------------------
# setting the initial value of each to the same value.
initial_string <- stri_rand_lipsum(1)
comment_value <- reactiveValues(comment = initial_string,
submit = initial_string)
# Event observers ----------------------------------------------------
observeEvent(input$randtext,
{
comment_value$comment <- stri_rand_lipsum(1)
}
)
# This prevents the comment_value$submit from changing until the
# Submit button is clicked. It changes to the value of the input
# box, which is updated to a random value when the Random Comment
# button is clicked.
observeEvent(input$submit,
{
comment_value$submit <- input$comment
}
)
# Output Components -------------------------------------------------
# Generate the textAreaInput
output$randcomment <- renderUI({
textAreaInput("comment",
label = h3("Enter Course Comment"),
value = comment_value$comment,
height = '300px',
width = '300px')
})
# Generate the submitted text display
output$commenttext <-
renderText({
comment_value$submit
})
}
)
Some comments on your code
I struggled a little with determining what your code was doing. Part of the reason was that your server function was organized a bit chaotically. Your components are
output
reactive list
observer
output (but not assigned to a slot...superfluous)
reactive object
output
I'd recommend grouping your reactives together, your observers together, and your outputs together. If you have truly separate systems, you can break the systems into different sections of code, but have them follow a similar pattern (I would claim that these two boxes are part of the same system)
Your commentUi reactive has a strange if-else construction. It always sets com to a random string. What's more, the if-else construction isn't really necessary because no where in your code do you ever update comment_value$default--it is always 0. It looks like you may have been trying to base this off of an action button at some point, and then concluded (rightly) that that wasn't a great option.
Also, I would advise against building UI components in your reactive objects. You'll find your reactives are much more flexible and useful if they return values and then build any UI components within the render family of functions.
I have a rather complex Shiny application and something weird happens:
When I print out some of my intermediate steps the App makes, everything gets printed out twice. That means, everything gets evaluated etc. twice.
I know without seeing the progamme its rather hard to tell what causes the problem, but maybe someone can pin point me (based on experierence/knowledge) what might be the problem.
Like I mentioned in the comment, isolate() should solve your problem.
Beyond the documentation of Rstudio http://shiny.rstudio.com/articles/reactivity-overview.html
I recommend the following blog article for interesting informations beyond the RStudio docu.
https://shinydata.wordpress.com/2015/02/02/a-few-things-i-learned-about-shiny-and-reactive-programming/
In a nutshell, the easiest way to deal with triggering is to wrap your code in isolate() and then just write down the variables/inputs, that should trigger changes before the isolate.
output$text <- renderText({
input$mytext # I trigger changes
isolate({ # No more dependencies from here on
# do stuff with input$mytext
# .....
finishedtext = input$mytext
return(finishedtext)
})
})
Reproducible example:
library(shiny)
ui <- fluidPage(
textInput(inputId = "mytext", label = "I trigger changes", value = "Init"),
textInput(inputId = "mytext2", label = "I DONT trigger changes"),
textOutput("text")
)
server <- function(input, output, session) {
output$text <- renderText({
input$mytext # I trigger changes
isolate({ # No more dependencies from here on
input$mytext2
# do stuff with input$mytext
# .....
finishedtext = input$mytext
return(finishedtext)
})
})
}
shinyApp(ui, server)
I encountered the same problem when using brush events in plotOutput. The solution turned out to be resetOnNew = T when calling plotOutput to prevent changes in my plot causing the brush event to be evaluated again.
while working on a Shiny application I stumbled upon the following problem which seems related to the order in which input are changed by the update***Input vs. the reactivity order.
I have been able to narrow down the code and steps to reproduce the problem to the following ones:
I have a numericInput which spans between 1 and 5, with 3 as default value, whose selected value is used to produce some output (for the sake of simplicity, here it's just a "Good" message if the value is 2, 3 or 4, and a "Bad" message if the value is either 1 or 5);
I want the user to be able to change the input value and either use its chosen value (by pressing a Submit button) or use the default value (by pressing a Reset button) in the rest of the application;
The check for the condition 1<value<5 has to be preferably inside an isolate block (because my actual complete code triggers various time-consuming operations based on the input)
The code snippets are the following
ui.R:
shinyUI(fluidPage(
titlePanel(
fluidRow(headerPanel(HTML("Test a possible bug"), windowTitle = "Test a possible bug")
)
),
mainPanel(
tabsetPanel(
tabPanel("Try this", br(),
numericInput(inputId="foo", label="Input me", value=3,min=1, max=5),
actionButton(inputId="reset", label="Use default"),
actionButton(inputId="submit", label="Use new value"),br(),br(),br(),
textOutput(outputId="bar")
)
)
)
))
server.R:
shinyServer(function(input, output, session) {
observeEvent(input$reset, {
updateNumericInput(session=session, inputId="foo", value=3)
})
checkInput <- reactive({
input$submit
input$reset
isolate({
input$foo > 1 && input$foo < 5
})
})
output$bar <- renderText({
if (checkInput())
"Good"
else
"Bad"
})
})
The problem I encountered is the following
If I choose 5, the app properly prints a "Bad" message
If I now press "Use default" the numericInput is properly update to the default 3, but the message remains "Bad" because the modification of the input is not acknowledged (yet) by shiny
If I now press a second time the "Use default" button, or if I press the "Use new value" button, the message is now correctly updated to "Good"
I would expect on the other hand that shiny acknowledges the updated input, since the input field has changed
Is this behaviour by design? Any suggestion to solve the problem?
I could work around the issue by requiring the user to separately reset the value to default and then to submit the new value, but it sounds a little bit unsatisfactory...
p.s. my actual code has a dozen of numericInput fields, thus the "Use default" button is really needed because manually restoring all values is not really a feasible option outside the simplified settings posted here ;-)
I believe this is how it is intended to work. If you check the documentation, of updateNumericInput or updateSelectInput, the updation is done after all the outputs are produced.
"The input updater functions send a message to the client, telling it
to change the settings of an input object. The messages are collected
and sent after all the observers (including outputs) have finished
running."
I would suggest that the functionality be set in such a way that the Message "good' or 'bad' be displayed only when 'Submit' is hit, AND that it is 'cleared' when "Reset' is hit. Hope this is useful
Please see an example
library(shiny)
ui<-(fluidPage(
titlePanel(
fluidRow(headerPanel(HTML("Test a possible bug"), windowTitle = "Test a possible bug")
)
),
mainPanel(
tabsetPanel(
tabPanel("Try this", br(),
numericInput(inputId="foo", label="Input me", value=3,min=1, max=5),
actionButton(inputId="reset", label="Use default"),
actionButton(inputId="submit", label="Use new value"),br(),br(),br(),
textOutput(outputId="bar")
)
)
)
))
server<-(function(input, output, session) {
rv <- reactiveValues()
observeEvent(input$reset, {
updateNumericInput(session=session, inputId="foo", value=3)
rv$Message = " "
})
observeEvent(input$submit,{
rv$checkInput<- input$foo > 1 && input$foo < 5
if (rv$checkInput)
rv$Message<- "Good"
else
rv$Message<- "Bad"
})
output$bar <- renderText({
rv$Message
})
})
shinyApp(ui,server)