R 闪亮检查文本输入为数字

R SHINY CHECK TEXT INPUT AS NUMERIC

我想检查用户在用户界面中输入的内容是否为数字,如果 return 出现 SafeError。我写了下面的代码但是它给我错误,你能帮我吗?

ui <- fluidPage( 
sidebarLayout( 
sidebarPanel(
  
  textInput("price","Price:", value = "", placeholder = "00.0"),
), 


mainPanel(

h5(textOutput("price")),

)))


server <- function(input, output){  
output$price <- renderText(
if(input$price == "" || is.numeric(input$pirce)==FALSE)
   stop(safeError("input correct price field"))
else
   return(c("Price:",input$price))
)                       
}

shinyApp(ui = ui, server = server)


    
在您执行 as.numeric(input$price) 之前,

input$price 仍然是一个字符。如果模式与数字匹配,您可以使用正则表达式搜索文本:

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      textInput("price", "Price:", value = "", placeholder = "00.0"),
    ),
    mainPanel(
      h5(textOutput("price")),
    )
  )
)


server <- function(input, output) {
  output$price <- renderText(
    if (!stringr::str_detect(input$price, "^[0-9]+[.]?[0-9]*$")) {
      stop(safeError("input correct price field"))
    } else {
      return(c("Price:", input$price))
    }
  )
}

shinyApp(ui = ui, server = server)

您可以使用 as.numeric:

检查
library(shiny)

ui <- fluidPage( 
  sidebarLayout( 
    sidebarPanel(
      textInput("price","Price:", value = "", placeholder = "00.0"),
    ), 
    mainPanel(
      h5(textOutput("price")),
    )
  )
)


server <- function(input, output, session){  
  
  output$price <- renderText({
    check <- as.numeric(input$price)
    
    if(is.na(check)){
      stop(safeError("input correct price field"))
    }else{
      return(c("Price:",input$price))
    }
  })                       
}

shinyApp(ui = ui, server = server)