I am learning Shiny and want to run the following basic function. The function simply identifies the class of an object specified in its first (and only) argument.
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)
}
I want to specify the argument in Shiny via a textInput function as follows:
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)
However, when the check_data_type program is specified via a Shiny UI, the program always classifies the value I enter via the textInput field as "character."
The textInput function, as its name might suggest, appears to be automatically classifying any value it receives as "character" before it is evaluated by the check_data_type function.
I assume this is what's happening because if instead I try to run the following simple arithmetic function within Shiny...
square_the_number = function(sample_Variable) {
return(sample_variable^2)
}
...I need to first deliberately convert the value entered via the textInput function to a numerical value via the as.numeric() function. To illustrate, when I call the above function within the Shiny server function (see second-to-last line in block below) the program executes properly. Otherwise it will return "Error: non-numeric argument to binary operator."
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)
Is there any way to get the textInput function to be class-agnostic so that it will properly classify numeric values via the aforementioned check_data_type function?
I considered the numericInput function but that forces you to specify a drop-down menu and I'd like to keep the input field open-ended.
numericInput()
? - amrrs