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

如何在R Shiny中通过单选按钮控制函数参数(vtree示例)

在Shiny中动态切换vtree的Prune参数

问题背景

这是此前问题《Dynamic change in vtree within shiny: How to deselect》的后续。尝试通过单选按钮切换vtree包的prunesmaller和prunebigger参数,原代码的if else写法存在语法错误,无法实现参数切换效果。

核心需求

在R Shiny中通过单选按钮动态调整函数的任意参数(此处为vtree的修剪参数)。

修正后的完整代码

library(shiny)
library(vtree)

# Define UI ----
ui <- pageWithSidebar(
  # App title ----
  headerPanel("Cyl vtree"),
  # Sidebar panel for inputs ----
  sidebarPanel(
    radioButtons("smaller_bigger", h3("Prune smaller or bigger?"), choices = c("smaller", "bigger"), inline = TRUE),
    sliderInput(inputId = "prune", label = "Number to prune?", step = 10, min = 0, max = 100, value = 0),
    selectizeInput("level", label = "Level", choices = NULL, multiple=TRUE),
    selectizeInput("values", label= "Values", choices = NULL, multiple=TRUE),
  ),
  # Main panel for displaying outputs ----
  mainPanel(
    vtreeOutput("VTREE")
  )
)

# Define server logic to plot ----
server <- function(input, output,session) {
  df <- reactiveVal(mtcars)
  vector <- c("cyl","vs", "am","gear")
  
  observe({
    updateSelectizeInput(session, "level", choices = colnames(df()[vector]), selected = NULL) 
    updateSelectizeInput(session, "values", choices = unique(df()$cyl))
  })
  
  output[["VTREE"]] <- renderVtree({
    # 直接在参数中通过条件赋值实现动态切换
    vtree(df(), c(input$level),
          sameline = TRUE,
          follow = list(cyl = input$values),
          prunesmaller = if(input$smaller_bigger == "smaller") input$prune else NULL,
          prunebigger = if(input$smaller_bigger == "bigger") input$prune else NULL
    )
  })
}

shinyApp(ui, server)

关键代码解释

原代码的错误在于不能在函数调用的参数列表中直接使用块级的if else语句。修正方案采用了更简洁的参数条件赋值:

  • 当单选按钮选中smaller时,给prunesmaller赋值为滑块输入值,prunebigger设为默认值NULL
  • 当单选按钮选中bigger时,给prunebigger赋值为滑块输入值,prunesmaller设为默认值NULL

如果需要处理更复杂的动态参数场景(比如参数名也是动态的),可以用do.call构建参数列表:

output[["VTREE"]] <- renderVtree({
  # 构建基础参数列表
  base_args <- list(
    data = df(),
    vars = c(input$level),
    sameline = TRUE,
    follow = list(cyl = input$values)
  )
  # 构建动态prune参数
  prune_arg <- if(input$smaller_bigger == "smaller") {
    list(prunesmaller = input$prune)
  } else {
    list(prunebigger = input$prune)
  }
  # 合并参数并调用vtree
  do.call(vtree, c(base_args, prune_arg))
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 11:10:22