我想有一个UI,允许用户给予一定的输入,如果他需要更多的输入,他应该能够点击一个按钮,然后打开新的输入。多亏了这个条目,一切都解决了。
然而,现在我想从这些输入中创建一个数据框,我正在努力解决这个问题。这是我的代码:
library(shiny)
ui <- fluidPage(
fluidRow(
column(
width = 6,
uiOutput("selection_ui")
),
column(
width = 3,
uiOutput("amount_ui")
),
column(
width = 3,
uiOutput("year_ui")
)
),
fluidRow(
column(
width = 6,
actionButton(inputId = "addEntry",
label = "Add Entry")
),
column(
width = 6,
actionButton(inputId = "deleteEntry",
label = "Delete Entry")
)
),
br(),
fluidRow(
column(
width = 12,
actionButton(inputId = "Go",
label = "Submit")
)
),
dataTableOutput("Dataframe")
)
server <- function(input, output){
counter <- reactiveValues(value = 1)
AllInputs <- reactive({
x <- reactiveValuesToList(input)
})
observeEvent(input$addEntry, {
counter$value <- counter$value + 1
})
observeEvent(input$deleteEntry, {
req( counter$value >= 2 )
counter$value <- counter$value - 1
})
selection <- reactive({
n <- counter$value
if(n > 0){
isolate({
lapply(seq_len(n), function(i){
selectInput( inputId = paste0("select",i),
label = paste0(i, "-th selection:"),
choices = as.list(c("", "A", "B", "C")),
selected = AllInputs()[[paste0("select",i)]]
)
})
})
}
})
amount <- reactive({
n <- counter$value
if(n > 0){
isolate({
lapply(seq_len(n), function(i){
numericInput(inputId = paste0("number",i),
label = paste0(i, "-th amount:"),
value = AllInputs()[[paste0("number",i)]])
})
})
}
})
year <- reactive({
n <- counter$value
if(n > 0){
isolate({
lapply(seq_len(n), function(i){
numericInput(inputId = paste0("year",i),
label = paste0(i, "-th year:"),
value = AllInputs()[[paste0("year",i)]])
})
})
}
})
output$selection_ui <- renderUI({selection()})
output$amount_ui <- renderUI({amount()})
output$year_ui <- renderUI({year()})
eventReactive(input$Go, {
df <- data.frame(CREATE DATAFRAME HERE)
})
output$dataframe <- renderDataTable(df())
}
shinyApp(ui = ui, server = server)
我想我用sapply()
解决了这个问题:
df <- eventReactive(input$Go, {
n <- counter$value
tmp1 <- sapply(seq_len(n), function(i){
input[[paste0("select",i)]]
})
tmp2 <- sapply(seq_len(n), function(i){
input[[paste0("number",i)]]
})
tmp3 <- sapply(seq_len(n), function(i){
input[[paste0("year",i)]]
})
data.frame(col1 = tmp1,
col2 = tmp2,
col3 = tmp3
)
})