You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shiny中renderText()渲染公式异常,~符号位置错误

问题解决:Shiny中公式显示顺序错乱

你的问题出在用paste()处理formula对象上。当你执行paste(formula_to_estimate())时,R会把formula拆解成三个元素的向量("~"、响应变量名、解释变量名),默认用空格拼接后就会出现~ relative_excess Periodo的错误格式。

两种修复方案:

方案1:用deparse()正确转换formula为字符串

修改server部分的renderText代码:

output$formula_to_estimate_1 = renderText({
  deparse(formula_to_estimate())
})

deparse()会将formula对象直接转为符合预期的公式字符串,比如relative_excess ~ Periodo。

方案2:直接生成公式字符串(若仅用于显示)

如果不需要实际的formula对象,只是要显示公式文本,可以直接在reactive中生成字符串:

formula_to_estimate = reactive({
  paste0(input$var_to_forecast_CF1, "~", "Periodo")
})

output$formula_to_estimate_1 = renderText({
  formula_to_estimate()
})

完整修复后的代码示例:

library(shiny)

ui <- fluidPage(
    titlePanel("Formula not showing correctly"),
    
    shinyWidgets::pickerInput(
      inputId = "var_to_forecast_CF1",
      label = h4("Variable To Predict"),
      choices = c("Total_Deaths", "relative_excess"),
      selected = "Total_Deaths"
    ),
    
    verbatimTextOutput("formula_to_estimate_1")
)

server <- function(input, output) {
  formula_to_estimate = reactive({
    paste0(input$var_to_forecast_CF1, "~", "Periodo") %>% 
      as.formula()
  })
  
  output$formula_to_estimate_1 = renderText({
    deparse(formula_to_estimate())
  })
}

shinyApp(ui = ui, server = server)

内容的提问来源于stack exchange,提问作者user113156

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 06:41:17