Producing dynamic/multiple input boxes to collect

2020-05-03 13:04发布

问题:

I am trying to build an app in Shiny that (1) asks user for number of Assets in his/her portfolio. Depending on the numeric entry, (2) the user is presented with one numeric box to enter the % of portfolio owned AND the Ticker/name of the Asset. For instance, If the user enters 3 for number of assets in portfolio, he will be presented with something like this:

Asset1 ----> Enter ticker______ Enter Wight______

Asset2 ----> Enter ticker______ Enter Wight______

Asset3 ----> Enter ticker______ Enter Wight______

This is suppose to be dynamic so the greater the number of assets, the greater the input fields. Finally, in step (3), I want to save the entered information for each Asset in a table and display the table.

Here is what I have got and it is no where near what I need it to be. I am totally new to Shiny and that is half the reason for my troubles:

UI.R

 shinyUI(pageWithSidebar (

  headerPanel( "Portfolio Returns"),

  sidebarPanel(

    numericInput("assets", label = "Enter Total Assets", value="")

  ),
 mainPanel(

tableOutput("table"))     
 )
) 

server.R

shinyServer(
  function(input,output) {
  output$DynamicAssets <- renderUI ({

  Assets <- as.integer(input$assets)

  for(i in 1:Assets,function(i) {
  "ticker" = textInput("Ticker", label="Enter Ticker", value="Enter Ticker"),

  "weight" = numericInput ("AssetWeight", label="weights of Assets", value="")

     })
    })

  })
 })

I know the code is in complete because i have no idea what to do next. this is all that i figured out from seraching the net. Your help would be greatly appreciated.

回答1:

ui.R

library(shiny)

shinyUI(pageWithSidebar (

  headerPanel( "Portfolio Returns"),

  sidebarPanel(
    numericInput("assets", label = "Enter Number of Assets in Portfolio", value="1"),
    uiOutput("tickers")
  ),
  mainPanel()
)) 

server.R
-Note that to pass multiple items in the renderUI() function you have to group them into a list, and here lapply() is creating a list of lists.

library(shiny)

shinyServer( function(input, output, session) {

  output$tickers <- renderUI({
    numAssets <- as.integer(input$assets)

    lapply(1:numAssets, function(i) {
      list(tags$p(tags$u(h4(paste0("Asset ", i)))),
           textInput(paste0("ticker", i), label = "Ticker Name", value = "Enter ticker..."),
           numericInput(paste0("weight", i), label = "Weight of Asset", value=0))  
    })
  })
})