Search code examples
rshinytextinput

Length of vector contains input from textInput widget


I have a complete R script which will do all calculations on captured (readline()) numbers, however I want to create application with user interface and I stuck at the beginning.

I am new in Shiny and I have a problem with simple calculation of the length of the vector caputred by inputText() widget. The problem is that regardless of the content of the vector, the result of the length function is always 1.

Thank you for help in advance.

ui.R - File

library(shiny)

shinyUI(fluidPage(

  titlePanel("Number App"),

  sidebarLayout(
    sidebarPanel("This is sidebar panel",
                 textInput("number", "Number:", value=""),
                 submitButton(text = "Submit Number", icon = NULL)
    ),
    mainPanel("This is main panel",
              textOutput("text1")
    )
  )
)) 

server.R

library(shiny)

shinyServer(function(input, output) {
  x <- reactive(as.numeric(input$number))
  y <- reactive(strsplit(as.character(x()), ""))
  z <- reactive(length(y()))

  output$text1 <- renderText({
    paste("Captured Number:", x(), "Splitted Number:", y(), "Length of Number: ",  z())
  }) 
})

Solution

  • Problem is simple, you wanted to find length of character vector, but strsplit return list. You have passed single input string and pattern, you can return first element of list (if any).

    Try this

    library(shiny)
    
    shinyServer(function(input, output) {
      x <- reactive(as.numeric(input$number))
      y <- reactive(strsplit(as.character(x()), "")[[1]])
      z <- reactive(length(y()))
    
      output$text1 <- renderText({
        paste("Captured Number:", x(), "\tSplitted Number:", y(), "\tLength of Number: ",  z())
      }) 
    })