要动态生成UI元素,您需要使用
renderUI
在服务器中,并将其分配给
uiOutput
在UI功能中。因为你只想在以下情况下渲染元素
WMA
功能已选择,您可以使用
req(input$selectDropdown == "WMA")
在
renderUI
电话。
req
评估表达式是否为“truthy”,并且仅在满足条件时执行以下代码。
由于您只有3种不同的功能选择,我认为您可以使用
if
这里的条款完全可以。
你的代码还有其他问题:
-
如果你生成一个
reactive
函数,您只需将其分配给函数名称,而不是
output$functionname
-
拼写错误
selectDropdown
而不是
selectedDropdown
-
我不知道什么是合理的输入
wts
争论。
numericInput
只返回一个值,但你需要一个长度为的向量
x
我刚用过
rep(input$weights, times = nrow(data))
使其发挥作用
library(shiny)
library(shinydashboard)
library(quantmod)
library(TTR)
ui <- dashboardPage(
dashboardHeader(title = "Basic dashboard"),
dashboardSidebar(
sidebarMenu(
menuItem("Dashboard", tabName = "dashboard", icon = icon("dashboard")),
menuItem("Widgets", tabName = "widgets", icon = icon("th"))
)
),
dashboardBody(
tabItems(
# First tab content
tabItem(tabName = "dashboard",
fluidRow(
box(plotOutput("plot1", height = 250)),
box(
title = "Controls",
sliderInput("slider", "Number of observations:", 1, 100, 50)
)
)
),
# Second tab content
tabItem(tabName = "widgets",
fluidPage(
titlePanel(title = h2("Algo Backtester", align = "center")),
sidebarPanel(
textInput("sym", "Symbol", "MSFT"),
selectInput(inputId = "selectDropdown", label = "dropdownChoice", choices = c("SMA", "EMA", "WMA")),
numericInput(inputId = "selectN", label = "selectedN", value = 3),
uiOutput(outputId = "weights_UI")
),
mainPanel(
tableOutput("modData"),
)
)
)
)
)
)
server <- function(input, output) {
set.seed(122)
histdata <- rnorm(500)
output$plot1 <- renderPlot({
data <- histdata[seq_len(input$slider)]
hist(data)
})
output$weights_UI <- renderUI({
req(input$selectDropdown == "WMA")
numericInput(inputId = "weights", label = "Weights", value = 1)
})
out <- reactive({
selectedDropdown <- input$selectDropdown
data <- getSymbols(Symbols = input$sym, src = "yahoo", index.class = "POSIXct", from = "2018-01-01", to = "2019-01-01", auto.assign = FALSE)
n = input$selectN
# wts = 1:5 # would like to modify here
# Apply selection to "data"
if(selectedDropdown == "SMA"){
SMA(Cl(data), n = n)
}
if(selectedDropdown == "EMA"){
EMA(Cl(data), n = n)
}
if(selectedDropdown == "WMA"){
WMA(Cl(data), n = n, wts = rep(input$weights, times = nrow(data)))
}
})
output$modData <- renderTable({
head(out())
})
}
shinyApp(ui, server)