R亮晶晶地将文本输入选为数字



我想检查用户在用户界面中写入的输入是否是数字,以防返回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)


input$price在执行as.numeric(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)

相关内容

  • 没有找到相关文章

最新更新