r - 为什么 `R` 管道运算符 `|>` 在使用 Shiny 的响应式(Reactive)编程中不起作用?

标签 r shiny shiny-server shiny-reactivity

我想在使用 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/

相关文章:

r - 实时运行 Shiny 的R renderPlots

r - 在 Shiny 的面板中绘制两个图形,一个图形在另一个图形下方

r - Shiny 的仪表板主板高度问题

r - 创建 Shiny 的 react 变量,指示最后修改哪个小部件

r - 选择输入 : Have Multiple = TRUE and filter based off that

R - 计算 Shiny 下载按钮的点击次数

r - 'T' & 'F' 从数据库中读取为 True 和 False

r - ESS 调用不同的 R 安装

javascript - Shiny 的应用程序以不同的设置开始

r - Shiny 的应用程序错误无法将类型 'environment' 强制转换为类型 'character' 的向量