Reputation: 798
I'm trying to create a shiny app where I can input a regression formula and get an output of the results. I tried this:
library(shiny)
ui <- fluidPage(
titlePanel("Text Input"),
sidebarLayout(
sidebarPanel(
textInput(inputId = "text1",
label = "Regression"),
value = "Enter formula"),
mainPanel(
verbatimTextOutput("text1"),
verbatimTextOutput("regout")
)
)
)
server <- function(input, output, session) {
output$text1 <- renderPrint({
input$text1
})
formula <- reactive(input$text1)
output$regout <- renderPrint({
summary(formula)
})
}
shinyApp(ui = ui, server = server)
In the app, I try to input this
lm(mpg ~ disp + wt, data = mtcars)
But I'm getting this error:
Error: object of type 'closure' is not subsettable
What does object of type 'closure' mean, and how can I make it work?
Upvotes: 1
Views: 89
Reputation: 84529
You miss the parentheses: summary(formula())
. But if you type lm(mpg ~ disp + wt, data = mtcars)
you will get the string "lm(mpg ~ disp + wt, data = mtcars)"
. This will not run the code lm(mpg ~ disp + wt, data = mtcars)
.
You could enter mpg ~ disp + wt
and do:
lmformula <- reactive({
tryCatch({
as.formula(input$text1)
}, error = function(e) NULL)
})
lmreg <- reactive({
if(!is.null(lmformula())){
tryCatch({
lm(lmformula(), data = mtcars)
}, error = function(e) NULL)
}
})
lmsummary <- reactive({
if(!is.null(lmreg())){
summary(lmreg())
}
})
output$regout <- renderPrint({
lmsummary()
})
Upvotes: 2
Reputation: 61
Any render function is already a reactive context so you don't need to declare the formula variable as its own reactive. The error message is pretty ubiquitous but I'm assuming it's popping up due to this weird nature of having a reactive context within a reactive context, although I believe that it isn't explicitly forbidden. Anyway here's what the code should look like in the server function.
server <- function(input, output, session) {
output$text1 <- renderPrint({
input$text1
})
output$regout <- renderText({
summary(input$text1)
})
}
You will get something like this is at the output since we haven't regressed anything yet.
1 character character
It might get tricky defining your own formula, since you usually pass them as a string literal into the lm()
function. But yeah that's all I got, good luck!
Upvotes: 0