Search code examples
rshinyshiny-server

How to recode shiny ui.r numeric values in server.r for main panel outputs?


I'm building a shiny app where I have a series of numeric inputs as below. Users can enter values from 1-9 for the 10 inputs. The goal is to produce some plots that account for a server.r recoding of the 1-9 values to be 1-3 (i.e., 1-3 = 1, 4-6=2, 7-9=3). I've tried using various recoding functions on server.r but all result in an error: 'Attempted to assign a value to a read-only reactivevalues object'. Below is my ui.r and server.r code where I ultimately would like the barplot to reflect the recoded numeric input values.

**ui.R code**

library(shiny)
shinyUI(fluidPage(
titlePanel("Short Form Web App"),  

sidebarPanel(
  numericInput("i1", label = h5("Intellectual Item 1"), min=1,max=9,value=1),
  numericInput("i3", label = h5("Intellectual Item 3"), min=1,max=9,value=1),
  numericInput("i6", label = h5("Intellectual Item 6"), min=1,max=9,value=1),
  numericInput("i9", label = h5("Intellectual Item 9"), min=1,max=9,value=1),
  numericInput("i11",label = h5("Intellectual Item 11"), min=1,max=9,value=1),    
  numericInput("a5", label = h5("Academic Item 5"), min=1,max=9,value=1),
  numericInput("a6", label = h5("Academic Item 6"), min=1,max=9,value=1),
  numericInput("a7", label = h5("Academic Item 7"), min=1,max=9,value=1),
  numericInput("a8", label = h5("Academic Item 8"), min=1,max=9,value=1),
  numericInput("a9", label = h5("Academic Item 9"), min=1,max=9,value=1)
  ),

  mainPanel(
   plotOutput("distPlot1"))))

**server.R code**

library(shiny)

shinyServer(function(input, output) {   
 output$distPlot1 <- renderPlot({
 x<- cbind(input$i1, input$i3, input$i6, input$i9, input$i11)
 bins <- seq(min(x), max(x))
 barplot(height = x,names.arg=c("Item 1", "Item 3","Item 6","Item 9","Item 11"))    
 })
 })

Solution

  • I suggest to modify your function inside shinyServer as follows:

    shinyServer(function(input, output) {
        output$distPlot1 <- renderPlot({
            x <- cbind(input$i1, input$i3, input$i6, input$i9, input$i11)
            x <- apply(x, 2, function(x) ifelse(x<4,1, ifelse(x>6,3,2)))
            bins <- seq(min(x), max(x))
            barplot(height = x, names.arg = c("Item 1", "Item 3", "Item 6",
                "Item 9", "Item 11"))
        })
    })