【发布时间】:2016-03-22 07:51:47
【问题描述】:
所以几天前我问了以下问题,R Shiny Dynamic Input,虽然给出的问题的答案是正确的,但我现在想详细说明一下,因为我无法编辑给出的代码来回答我的新问题。所以最初我希望能够让用户指定一个数字,比如 k,然后动态生成 k 个字段供用户填写。现在,给出的代码假定输出是数字,但是,我希望用户能够在 1,...,k 字段中的每个字段中指定一个包含 5 个值的向量。由于在指定 k 之后,输入将是长度为 5 的数值的 k 个向量,因此我希望能够将这些值存储在 k x 5 矩阵中。这样我以后可以使用这些值进行数据操作。如果有帮助,这里是原始答案中的代码:
library(shiny)
ui <- shinyUI(fluidPage(
titlePanel("Old Faithful Geyser Data"),
sidebarLayout(
sidebarPanel(
numericInput("numInputs", "How many inputs do you want", 4),
# place to hold dynamic inputs
uiOutput("inputGroup")
),
# this is just a demo to show the input values
mainPanel(textOutput("inputValues"))
)
))
# Define server logic required to draw a histogram
server <- shinyServer(function(input, output) {
# observe changes in "numInputs", and create corresponding number of inputs
observeEvent(input$numInputs, {
output$inputGroup = renderUI({
input_list <- lapply(1:input$numInputs, function(i) {
# for each dynamically generated input, give a different name
inputName <- paste("input", i, sep = "")
numericInput(inputName, inputName, 1)
})
do.call(tagList, input_list)
})
})
# this is just a demo to display all the input values
output$inputValues <- renderText({
paste(lapply(1:input$numInputs, function(i) {
inputName <- paste("input", i, sep = "")
input[[inputName]]
}))
})
})
# Run the application
shinyApp(ui = ui, server = server)
编辑
这里是更新的代码,但仍然不能完全工作:
library(shiny)
ui <- shinyUI(fluidPage(
titlePanel("Old Faithful Geyser Data"),
sidebarLayout(
sidebarPanel(
numericInput("numInputs", "How many inputs do you want", 4),
# place to hold dynamic inputs
uiOutput("inputGroup")
),
# this is just a demo to show the input values
mainPanel(tableOutput("inputValues"))
)
))
# Define server logic required to draw a histogram
server <- shinyServer(function(input, output) {
# observe changes in "numInputs", and create corresponding number of inputs
observeEvent(input$numInputs, {
output$inputValues <- renderTable({
all <- paste(lapply(1:input$numInputs, function(i) {
inputName <- paste("input", i, sep = "")
input[[inputName]]
}))
matrix <- as.matrix(all, ncol=5)
as.data.frame(matrix)
})
})
# this is just a demo to display all the input values
output$inputValues <- renderText({
paste(lapply(1:input$numInputs, function(i) {
inputName <- paste("input", i, sep = "")
input[[inputName]]
}))
})
})
# Run the application
shinyApp(ui = ui, server = server)
【问题讨论】: