2

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?

1 Answer 1

3

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)
4
  • I thought reactive should always be used with {}. What is the difference between reactive({}) and reactive()? :)
    – bird
    Sep 23, 2021 at 13:12
  • 1
    The difference is described here (see the examples). { returns the result of the last expression evaluated. In the above case NULL, which is passed to reactive's x argument. Sep 23, 2021 at 18:09
  • Do you know when I should and should not use {} with reactive()?
    – bird
    Sep 24, 2021 at 6:33
  • 1
    Joe Cheng explains his motivation of using curly braces here. The link to the videos over there is down, but you can find them here now. I don't think I can come up with a better explanation than him. Sep 24, 2021 at 7:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.