Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector input in shiny R and then use it

Tags:

r

shiny

In Shiny R, I want a simple way to take a vector as user input in ui.R and then want to use that in a function in server.R.I am new in shiny, please help.

like image 746
Indranil Bhattacharya Avatar asked Jan 20 '16 14:01

Indranil Bhattacharya


2 Answers

Here is something simple to get you started - good luck. And remember - next time post some code or you will surely get downvoted:

library(shiny)

u <- shinyUI(pageWithSidebar(

  headerPanel("Entering Vectors in Shiny"),
  sidebarPanel(
    textInput('vec1', 'Enter a vector (comma delimited)', "0,1,2")
  ),

  mainPanel(
    h4('You entered'),
    verbatimTextOutput("oid1"),
    verbatimTextOutput("oid2")
  )
))

s <- shinyServer(function(input, output) {

  output$oid1 <- renderPrint({
    cat("As string:\n")
    cat(input$vec1)
    }
    )

  output$oid2<-renderPrint({
    x <- as.numeric(unlist(strsplit(input$vec1,",")))
    cat("As atomic vector:\n")
    print(x)
  }
  )
}
)
shinyApp(ui = u, server = s)

Yielding:

enter image description here

like image 59
Mike Wise Avatar answered Sep 19 '22 07:09

Mike Wise


I am aware this is an old post but I have come across an alternative way for a user to enter a vector as Shiny input - using the create = TRUE and multiple = TRUE options with selectizeInput(). Slightly modifying Mike Wise's code example from above:

library(shiny)

ui <- shinyUI(

  pageWithSidebar(

    headerPanel("Entering Vectors in Shiny")

    , sidebarPanel(

      selectizeInput(
        "vec1"
        , "Enter a vector"
        , choices = NULL
        , multiple = TRUE
        , options = list(create = TRUE)
      )

    ),

    mainPanel(

      h4("You entered")

      , verbatimTextOutput("oid1")

      , verbatimTextOutput("oid2")

    )

  )
)

server <- shinyServer(function(input, output) {

  output$oid1 <- renderPrint({

    req(input$vec1)

    cat("As string:\n")
    cat(input$vec1)

  })

  output$oid2 <- renderPrint({

    req(input$vec1)

    cat("As atomic vector:\n")
    print(as.numeric(input$vec1))

  })

})

shinyApp(ui = ui, server = server)

enter image description here


enter image description here

like image 42
conrad-mac Avatar answered Sep 23 '22 07:09

conrad-mac