【发布时间】:2017-11-15 13:36:40
【问题描述】:
# ui.R
shinyUI(
fluidPage(
titlePanel("Make a data frame and display"),
fluidRow(column(4,selectInput('types', 'Select the type',c("Basketball","Soccer")))),
uiOutput('typeChange'),
mainPanel(dataTableOutput('displayDf'))
)
)
我正在尝试接受用户输入并将数据存储到数据框中。然后,我想在用户继续添加记录时同时显示数据框。上面的代码让用户在 Basketball 和 Soccer 之间进行选择
# server.R
# Create a function to initiate and clear global variables
clear_all <- function(){
z <<- c()
z1 <<- c()
z2 <<- c()
z3 <<- c()
}
clear_all()
shinyServer(function(input, output, session) {
# make additional ui depending on the sport selected.
output$typeChange <- renderUI({
if (input$types=="Basketball"){
clear_all()
fluidRow(
column(4,textInput("v1","Player name")),
column(4,selectInput("v2", "Age:",c("20","25","30"))),
column(4,actionButton("add", "Add the above player")))
}else if (input$types=="Soccer"){
clear_all()
fluidRow(
column(4,textInput("v1","Player name")),
column(4,selectInput("v2", "Age",c("20","25","30"))),
column(4,selectInput("v3", "Income:",c("100","125","150"))),
column(4,actionButton("add", "Add the above player")))
}else{}
})
# if a user adds a player, update the dataframe and display
observeEvent(input$add, {
if (input$types=="Basketball"){
z1 <<- c(z1,input$v1)
z2 <<- c(z2,input$v2)
z<<- data.frame(Player=z1,Age=z2)
}else if (input$types=="Soccer"){
z1 <<- c(z1,input$v1)
z2 <<- c(z2,input$v2)
z3 <<- c(z3,input$v3)
z<<- data.frame(Player=z1,Age=z2,Income=z3)
}
output$displayDf=renderDataTable(z)
})
})
服务器端代码根据选择的运动创建新文本和选择输入。我正在尝试创建的功能是,在选择一项运动后,用户可以输入其他输入并添加玩家。只要用户没有选择其他运动,就应该显示用户添加的球员列表。一旦用户更改了运动,数据框将是空的,并且不会显示之前运动的任何内容。
我面临的问题是,如果我在篮球中添加 3 名球员,然后将我的首选更改为足球,我仍然会看到篮球数据,直到我添加一名足球运动员。我希望在更改运动后立即隐藏显示的数据框。还附上相同的截图。请指教。
【问题讨论】:
-
我很确定问题是
z没有更新为input$types。 (z仅通过input$v1更新至input$v3)。当input$types改变时,它查询server端,它通过observeEvent查找(因为它包含input$types),但是z没有改变,因此renderDataTable 什么也不做。使z直接响应input$types应该可以解决您的问题。