我想在使用 Shiny
进行响应式(Reactive)编程时,在最新版本的 R
中使用管道运算符 |>
。例如,当我在 server
函数中使用 |>
时,如下所示:
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)
我收到此错误:
Listening on http://127.0.0.1:4346
Warning: Error in : `env` must be an environment
56: <Anonymous>
Error : `env` must be an environment
当我对服务器功能进行轻微更改时,此错误得到修复,如下所示:
server <- function(input, output, server) {
message <- reactive({paste0("You are ", input$age, " years old")})
output$message <- renderText(message())
}
但是,我希望能够在我的 Shiny
应用中使用管道运算符。我在 Shiny 的应用程序中使用 |>
的方式有什么问题?
最佳答案
问题是,您将空表达式 {}
传递给 reactive
的第一个参数(x 参数:reactive(x = {})
)。
使用上面的代码,管道 |>
将其表达式传递给 reactive
的第二个参数 env
,这会导致您收到错误。请参阅?响应式(Reactive)
这有效:
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)
关于r - 为什么 `R` 管道运算符 `|>` 在使用 Shiny 的响应式(Reactive)编程中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69281334/