【发布时间】: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 的问题是
-
我的领域没有开放吗?