2017-07-28 40 views
0

我試圖建立一個簡單的滾輪,在那裏你可以點擊一個按鈕並填充一系列變量。我確信這是一個簡單的解決方案,但我只是很難讓它工作。如何在單擊操作按鈕後填充變量?

這就是我得到的。我設置的界面就像我想要的那樣,但基本上我想爲強度行獲得新的值。

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) 

回答

0

您無法讀取強度變量,因爲它是在另一個函數中設置的。您可以創建一個共享反應值的向量

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

相關問題