user63230 user63230 - 3 months ago 12
R Question

Shiny plot simple curves by changing coefficient values

I'm new to Shiny and think this is a very simple question but can't figure it out. Essentially I have regression coefficients saved (

p1,p2
) and want to plot and visualize the resulting curves by varying both coefficient values with a slider.

Simplified version below. I am not sure how to extract each coefficient value from
p1,p2
and use it in the simple quadratic model here. Obviously using p1[i] is wrong but not sure what to do instead.

ui.R:

library(shiny)
shinyUI(fluidPage(
titlePanel("title"),
sidebarLayout(
sidebarPanel(
sliderInput("p1",
"Change P1",min = 110,max = 130,value = 120),
sliderInput("p2",
"Change p2", min = 90, max = 110,value = 100)
),
mainPanel(
plotOutput("distPlot")
)
)
))


server.R:

library(shiny)
xx<-data.frame(time1=seq(0,24))
p1=seq(110,130)
p2=seq(90,110)
shinyServer(function(input, output) {
output$distPlot <- renderPlot({
time1<-xx[,1]
y<-p1[i] + time1 + p2[i]*(time1^2)
plot(time1,y)
})

})


Any help appreciated. Thanks

Answer

I did a couple things. Firstly I changed y<-p1[i] + time1 + p2[i]*(time1^2) to y<- input$p1 + time1 + input$p2 * (time1^2). In shiny use input$[variableName] to get values from ui inputs.

I also added ylim = c(0,75000) to your plot just so you can visualize the change in the curve a little better.

CODE:

 library(shiny)

xx<-data.frame(time1=seq(0,24))

server <- shinyServer(function(input, output) {
  output$distPlot <- renderPlot({
    time1<-xx[,1]
    y<-input$p1 + time1 + input$p2*(time1^2)
    plot(time1,y,ylim = c(0,75000))
  })

})

ui <- shinyUI(fluidPage(
  titlePanel("title"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("p1",
                  "Change P1",min = 0,max = 10000,value = 100),
      sliderInput("p2", 
                  "Change p2", min = 90, max = 110,value = 100)
    ),
    mainPanel(
      plotOutput("distPlot")
    )
  )
))

shiny::shinyApp(ui=ui,server=server)