【问题标题】:Does the Shiny textInput function work with a numerical data input?Shiny textInput 函数是否适用于数字数据输入?
【发布时间】:2018-07-12 14:39:49
【问题描述】:

我正在学习 Shiny 并想运行以下基本功能。该函数只是识别在其第一个(也是唯一一个)参数中指定的对象的类。

check_data_type = function(sample_variable) {
  type = class(sample_variable)
  if (type=='numeric') {
    print("Data type is numeric")
    output = 1
  } else {
    print(paste0('Data type is ', type))
    output = 2
  }
  return(output)
}

我想通过 textInput 函数在 Shiny 中指定参数,如下所示:

library(shiny)

ui <- fluidPage(
  textInput(inputId = "keystroke_input", label = "Enter one keystroke here", 
value = NULL),
  textOutput(outputId = "keystoke_class"),
  actionButton("go","Run Function")
)

server <- function(input, output) {
  observeEvent(input$go,
  output$keystoke_class <- renderText({
    check_data_type(input$keystroke_input)
  })
  )
}

shinyApp(ui = ui, server = server)

但是,当 check_data_type 程序通过 Shiny UI 指定时,程序总是将我通过 textInput 字段输入的值分类为“字符”。

textInput 函数,顾名思义,似乎会在 check_data_type 函数评估它之前自动将它接收到的任何值分类为“字符”。

我认为这是正在发生的事情,因为如果我尝试在 Shiny 中运行以下简单的算术函数...

square_the_number = function(sample_Variable) {
  return(sample_variable^2)
}

...我需要先故意将通过 textInput 函数输入的值通过 as.numeric() 函数转换为数值。为了说明,当我在 Shiny 服务器函数中调用上述函数时(参见下面块中的倒数第二行),程序正确执行。否则它将返回“错误:二进制运算符的非数字参数。”

ui <- fluidPage(
  textInput(inputId = "keystroke_input", label = "Enter one keystroke here", 
value = NULL),
  textOutput(outputId = "keystoke_class"),
  actionButton("go","Run Function")
)

server <- function(input, output) {
  observeEvent(input$go,
  output$keystoke_class <- renderText({
    square_the_number(as.numeric(input$keystroke_input))
  })
 )
}

shinyApp(ui = ui, server = server)

有没有办法让 textInput 函数与类无关,以便通过上述 check_data_type 函数正确分类数值?

我考虑过 numericInput 函数,但它会强制您指定下拉菜单,并且我希望输入字段保持开放式。

【问题讨论】:

  • 你试过numericInput()吗?
  • 是的,如我原始帖子末尾所示。 numericInput 的问题是
  • 我的领域没有开放吗?

标签: r shiny


【解决方案1】:

numericInput() 就是你要找的东西。

ui <- fluidPage(
  numericInput(inputId = "keystroke_input", label = "Enter one keystroke here", 
            value = NULL),
  textOutput(outputId = "keystoke_class"),
  actionButton("go","Run Function")
)

server <- function(input, output) {


  observeEvent(input$go,
               output$keystoke_class <- renderText({
                 (input$keystroke_input)^2
               })
  )
}

shinyApp(ui = ui, server = server)

【讨论】:

    【解决方案2】:

    在 R shiny 中,我们有几个选项来提供输入。我们也有数字输入选项。检查显示所有可用选项的链接。还提供了其中每一个的代码。 http://shiny.rstudio.com/gallery/widget-gallery.html

    如果您是闪亮的新手,可以通过本教程学习 https://shiny.rstudio.com/tutorial/

    【讨论】:

      猜你喜欢
      • 2015-12-02
      • 1970-01-01
      • 1970-01-01
      • 2014-04-15
      • 2017-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多