Mastering Shiny Chapter 4 Exercise 3

I cannot understand what the problem with naming the variable var in exercise 2 and why does it suggest that the code will fail? I tried it in R with the following code and it works:

library(shiny)
ui <- fluidPage(
  textInput("var","var")
  )
server <- function(input, output, session) {
  var <- reactive(df[input$var])
  range <- reactive(range(var(), na.rm = TRUE))
}

shinyApp(ui, server)

https://mastering-shiny.org/basic-reactiercisesvity.html#ex-4

Thank you

Hint: Try to use renderText/textOutput to print the reactive variables range() and/or var().

Thanks for your reply. I tried to do that it gave me an error object of type 'closure' is not subsettable. I still do not fully understand why this is bad. I mean I would not name an input and a reactive with the same name but I don't think this is the real problem here.

The code may work, but the practice of naming objects, functions, reactives, etc. etc. after keywords or existing functions is bad practice

the code may work, but you are more likely to run into bugs or issues with your code later on. var() and range() are both functions that are present in base R and the stats package.

So what could end up happening is you think you are calling var() the reactive, but somewhere down the line, it may think that you are calling stats::var(). Hopefully that helps!

Ok that makes sense yes that's what I was thinking at first that it's just bad coding practice but the fact the Exercise says "Why will this code fail?" it totally put me off cause it does not seem like it would fail.

Perhaps the mastering shinybook should have posed a more complete reprex to consider ?

library(shiny)
ui <- fluidPage(
    textInput("var","var","Sepal.Length"),
    verbatimTextOutput("resulttext")
)
df <- iris
server <- function(input, output, session) {
    var <- reactive(df[input$var])
    range <- reactive(range(var(), na.rm = TRUE))
    
    output$resulttext <- renderText({
        req(range())
    })
}

shinyApp(ui, server)
Warning: Error in range: unused arguments (var(), na.rm = TRUE)

I think that more complete example would be helpful. If only to clarify that the code does not work, because range() is being defined as reactive data while already defined AND being used as range(), the stats function.

Keeping in mind that Programming in Shiny is similar to providing a recipe and the reactive graph determines the order in which the code is run:

  1. The code is telling shiny to use two different objects named var (i.e., input$var and var()) in it's recipe. That's not good, it's confusing. It's also difficult for a human to read...is var an input from the browser or a reactive data frame subset?
  2. The same is true for range(), is it supposed to be an R function or a reactive value in server?

The two sets of dual references in the code will confuse Shiny. The non-working example provided seems sufficient.