Home > Mobile >  Shiny doesn't renderText() for a formula correctly, puts ~ at the beginning
Shiny doesn't renderText() for a formula correctly, puts ~ at the beginning

Time:01-17

I am trying to renderText() some input to a formula. I want the user to select the input Y variable but the X variables are held fixed. When I run the code in RStudio, everything works fine, but when I try to see what formula is created I see that I have something wrong... i.e. I have ~ relative_excess Periodo where it should be: relative_excess ~ Periodo

Screenshot of error:

enter image description here

App:

#
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
#    http://shiny.rstudio.com/
#

library(shiny)

# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
    titlePanel("Formula not showing correctly"),
    
    shinyWidgets::pickerInput(
      inputId = "var_to_forecast_CF1",
      label = h4("Variable To Predict"),
      choices = c("Total_Deaths", "relative_excess"),
      selected = "Total_Deaths"
    ),
    
    
    verbatimTextOutput("formula_to_estimate_1")
)

# Define server logic required to draw a histogram
server <- function(input, output) {

  formula_to_estimate = reactive({
    #formula(paste0(input$var_to_forecast_CF1,  "~Periodo", sep = ""))
    paste0(input$var_to_forecast_CF1, "~", "Periodo") %>% 
      as.formula()
  })
  
  output$formula_to_estimate_1 = renderText({
    print(paste(formula_to_estimate()))
  })

}

# Run the application 
shinyApp(ui = ui, server = server)

CodePudding user response:

paste is the wrong way to convert an object to a string. The right way is either as.character (which is implicitly called by paste) or, in the case of language objects, deparse.

Since formulas are language objects in R, use deparse.

Furthermore, as Stéphane wrote, the print call is unnecessary here. This leaves us with:

output$formula_to_estimate_1 = renderText({
  deparse(formula_to_estimate())
})

CodePudding user response:

That should work if you don't apply as.formula. And you don't have to use print in renderText.

  • Related