如何在单击操作按钮后填充变量?

问题描述:

我试图建立一个简单的滚轮,在那里你可以点击一个按钮并填充一系列变量。我确信这是一个简单的解决方案,但我只是很难让它工作。如何在单击操作按钮后填充变量?

这就是我得到的。我设置的界面就像我想要的那样,但基本上我想为强度行获得新的值。

library(shiny) 
ui = fluidPage( 
    titlePanel(""), 
    sidebarLayout(  
    sidebarPanel(
     textInput("char_name","Name"), 
     textInput("char_sex","Sex"), 
     actionButton("rollButton", "Roll!", width = "100%"), 
     hr(), 
     helpText("Please consult _ if you need assitance.") 
    ), 
    mainPanel(
     htmlOutput("name"), 
     htmlOutput("sex"), 
     htmlOutput("natl"), 
     htmlOutput("strength") 
    ) 
) 
) 

server = function(input, output) { 
    observe({ 
    if(input$rollButton > 0) { 
     strength <- sum(sample(1:6,3,replace=TRUE)) 
    } 
    }) 
    output$name <- renderText({ 
    input$rollButton 
    isolate(paste0('<b>Name</b>: ', input$char_name)) 
    }) 
    output$sex <- renderText({ 
    input$rollButton 
    isolate(paste0('<b>Sex</b>: ', input$char_sex)) 
    }) 
    output$strength <- renderText({ 
    input$rollButton 
    isolate(paste0('<b>Strength</b>: ', strength)) 
    }) 
} 
shinyApp(ui = ui, server = server) 

您无法读取强度变量,因为它是在另一个函数中设置的。您可以创建一个共享反应值的向量

server = function(input, output) { 

    val <- reactiveValues(strength=NULL) 

    observe({ 
    if(input$rollButton > 0) { 
     val$strength <- sum(sample(1:6,3,replace=TRUE)) 
    } 
    }) 
    output$name <- renderText({ 
    input$rollButton 
    isolate(paste0('<b>Name</b>: ', input$char_name)) 
    }) 
    output$sex <- renderText({ 
    input$rollButton 
    isolate(paste0('<b>Sex</b>: ', input$char_sex)) 
    }) 
    output$strength <- renderText({ 
    input$rollButton 
    isolate(paste0('<b>Strength</b>: ', val$strength)) 
    }) 
} 
shinyApp(ui = ui, server = server) 
+0

我不确定这是否适用于其他变量。它的工作原理是嵌套在一个函数中很容易,但是我以不直接存储在函数中的方式转换所有数字。在单击提交按钮后,是否没有办法单独处理所有这些变量,然后让它们自动加载以供向量拾取? – Hanna

+0

我已经更新了我的答案,以便您可以在变量中设置值,并且渲染功能会检测到这一点 – tjjjohnson

+0

这很好用!你知道我如何可以多次变换变量比if(input $ rollButton> 0){}语句吗?我把这个值重新编码成一个强度类型的描述。我试着运行这两个语句,并最终必须合并roll和decode语句才能使其运行。 – Hanna