user330
user330

Reputation: 1270

Shiny: textInput does not respond in R

I wrote codes that get plots in shiny. I get the plots when I use plot(c(12,11)) as you can see in the codes, but when I use plot(c(input$ vec)) or plot(input$ vec) doe not give me to change the plots.

library(shiny)
library(ggplot2)
library(dplyr)
library(purrr)
ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      textInput('vec', 'Enter a vector (comma delimited)', "0,1")
    ),
    
    mainPanel(
      plotOutput(outputId = "distPlot"),
    )
  )
)
           
      server <- function(input, output) {
        output$distPlot <- renderPlot({
          qo <- function(x,m) { 
            p<-x^3+m^3
            return(p)
          }
          
          plot <- function(m) {
            ggplot(tibble(x = c(-10, 20)), aes(x)) +
              map(m, 
                  ~stat_function(fun = qo, aes(color = paste0("heat ", .)), args=list(m = .)))
            
          }
          plot(c(12,11))
          
        
      })
        }
shinyApp(ui,server)

Upvotes: 0

Views: 43

Answers (1)

stefan
stefan

Reputation: 124148

The issue is that input$vec is a character string. To use the input in your function you first have to split the string in single numbers and convert to numeric, e.g. using vec <- as.numeric(trimws(unlist(strsplit(input$vec, split = ",")))). Here I first split the string by , using strsplit, convert the resulting list to a vector using unlist, remove whitespace via trimws and finally convert to a numeric.

Afterwards you can apply your function:

library(shiny)
library(ggplot2)
library(dplyr)
library(purrr)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      textInput('vec', 'Enter a vector (comma delimited)', "0,1")
    ),
    
    mainPanel(
      plotOutput(outputId = "distPlot"),
    )
  )
)

server <- function(input, output) {
  output$distPlot <- renderPlot({
    qo <- function(x,m) { 
      p<-x^3+m^3
      return(p)
    }
    
    plot <- function(m) {
      ggplot(tibble(x = c(-10, 20)), aes(x)) +
        map(m, 
            ~stat_function(fun = qo, aes(color = paste0("heat ", .)), args=list(m = .)))
      
    }
    vec <- as.numeric(trimws(unlist(strsplit(input$vec, split = ","))))
    
    plot(vec)
    
  })
}
shinyApp(ui,server)

Upvotes: 2

Related Questions