Search code examples
rshinyshiny-servershiny-reactivity

Why does the `R` pipe operator `|>` not work in the reactive programming using Shiny?


I want to use the pipe operator |> in the latest version of R while doing reactive programming with Shiny. For example, when I use the |> in the server function like so:

library(shiny)

ui <- fluidPage(
    textInput("age", "How old are you?"),
    textOutput("message")
)

server <- function(input, output, server) {
    message <- paste0("You are ", input$age) |> reactive({})
    output$message <- renderText(message())
}

shinyApp(ui, server)

I get this error:

Listening on http://127.0.0.1:4346
Warning: Error in : `env` must be an environment
  56: <Anonymous>
Error : `env` must be an environment

This error is fixed when I make slight changes in my server function like so:

server <- function(input, output, server) {
        message <- reactive({paste0("You are ", input$age, " years old")})
        output$message <- renderText(message())
}

However, I would like to be able to use the pipe operator in my Shiny apps. What is wrong with the way I use |> in my shiny app?


Solution

  • The problem is, that you are passing an empty expression {} to reactive's first argument (x argument: reactive(x = {})).

    With your above code the pipe |> passes it's expression to reactive's second argument env, which results in the error you get. See ?reactive

    This works:

    library(shiny)
    
    ui <- fluidPage(
      textInput("age", "How old are you?"),
      textOutput("message")
    )
    
    server <- function(input, output, server) {
      message <- paste0("You are ", input$age) |> reactive()
      output$message <- renderText(message())
    }
    
    shinyApp(ui, server)