如何更新闪亮的checkboxGroupInput

时间:2017-10-12 11:23:08

标签: r shiny

作为了解Shiny的一种方式我正在为多个玩家开发一款小游戏。

我导入csv以检索我符合条件的玩家(players.csv),并且还包含一个带有textInput和actionButton的标签,以便随着时间的推移逐步添加其他符合条件的玩家。

我的下一步是从这些合格的玩家中选择那些希望玩某个特定游戏的玩家。我在后续的tabPanel上将此功能作为checkboxGroupInput提供。我此时没有考虑过使用玩家或游戏的查询。

我的问题是,如果我在第一步添加新玩家,我似乎无法更新checkboxGroupInput选项以反映我刚刚在第一步中添加的任何玩家。

为避免疑问......

  • 设置您自己的(类似的)file_path以将players.csv写入文件
  • 运行应用并在“add_a_player”和“play_game”标签之间切换
  • 你可以看到4名先前声明的合格球员(“john”,“paul”,“george”,“ringo”)从players.csv中读到
  • 通过'add_a_player'标签添加新玩家并按提交(新播放器附加到players.csv)
  • 返回'play_game'标签,但仍然只有4名玩家

问题 - 如何强制checkboxGroupInput也显示我刚添加的新播放器?

我已经蚕食各种不同的解决方案,但没有取得多大成功,包括尝试在updateCheckboxGroupInput上或通过conditionalPanel。

这是我的工作代码,非常感谢您的意见。 :)

library(shiny)


##########################  SETUP
file_path = "C:/Users/Callum Hollywood/Desktop/"
write.table(data.frame(player = c("john", "paul", "george", "ringo")),
        paste0(file_path, "players.csv"),
        col.names = T,
        row.names = F,
        sep = ",")
read_in_players = read.table(paste0(file_path, "players.csv"), header = T, stringsAsFactors = F, sep = ",")$player


########################## UI
ui = fluidPage(
navlistPanel(
tabPanel("add_a_player", 
         "add a player to the list of eligible players", 
         textInput("addplayer", ""),
         actionButton("submit", "SUBMIT")

),
tabPanel("play_game",
  checkboxGroupInput(inputId = "add_players",
                     label = "add players to a current game",
                     choices = read_in_players))))


##########################  SERVER
server = function(input, output){

players = eventReactive(input$submit,{input$addplayer}) 

observeEvent(input$submit,{
write.table(players(), paste0(file_path, "players.csv"), col.names = F, row.names = F, sep = ",", append = T)
})}

shinyApp(ui, server)

1 个答案:

答案 0 :(得分:1)

您可以按如下方式使用updateCheckboxGroupInput

server = function(input, output,session){

      players = eventReactive(input$submit,{input$addplayer}) 

      observeEvent(input$submit,{
        write.table(players(), paste0(file_path, "players.csv"), col.names = F, row.names = F, sep = ",", append = T)
        updateCheckboxGroupInput(session, inputId = "add_players", 
                                 choices = read.table(paste0(file_path, "players.csv"), header = T, stringsAsFactors = F, sep = ",")$player )

      })}

但是,每次添加播放器时阅读csv文件都不是一个好主意,您可以改为使用reactiveValues,如下所示:

 server = function(input, output,session){
      Allplayers=reactiveValues(Val = read_in_players)

      players = eventReactive(input$submit,{input$addplayer}) 

      observeEvent(input$submit,{
        write.table(players(), paste0(file_path, "players.csv"), col.names = F, row.names = F, sep = ",", append = T)
        Allplayers$Val <- c( Allplayers$Val,players())
        updateCheckboxGroupInput(session, inputId = "add_players", choices = Allplayers$Val)

      })}