我对 Shiny 还比较陌生。几周前,我创建了一个 NBA 获胜概率模型,并一直在尝试创建一个 Shiny 的应用程序,该应用程序将从我的模型生成输出,我已为其创建了用户定义的函数。
在我的用户界面中,我想要一个地方来输入“家乡积分”、“离开积分”和“剩余时间”的数字输入值。一旦为这些值输入了值,我希望用户单击操作按钮。单击操作按钮后,我只想让应用程序在主面板中显示我的函数的输出。但是,我无法弄清楚如何让它发挥作用。
这是我的代码:
library(shiny)
# Define UI for application that calculates win probability
ui <- fluidPage(
# Application title
titlePanel("Win Probability"),
# Sidebar layout with inputs and output definitions
sidebarLayout(
#sidebar panel for inputs
sidebarPanel(
#Add numeric input for home team points
numericInput(inputId = "home.pts", label = h3("Home Points"), value = 0),
#Add numeric input for away team points
numericInput(inputId = "away.pts", label = h3("Away Points"), value = 0),
#Add numeric input for time remaining in fourth quarter
numericInput(inputId = "time", label = h3("Time Remaining"), value = 0),
#Add action buttion
actionButton("goButton","Apply")),
# Show output
mainPanel(
verbatimTextOutput("win_prob")
)))
win_prob <- function(time, home.pts, away.pts) {
#calculate point difference
diff <- home.pts - away.pts
#Store intercept and betas
intercept <- 0.09564935
b_time <- 0.01087832
b_diff <- 0.5243092
b_interact <- -0.03066952
#calculate and store logit
logit <- intercept + (time*b_time) + (diff*b_diff) +
((time*diff)*b_interact)
#function to change logit to probability
logit2prob <- function(logit) {
odds <- exp(logit)
prob <- odds/(1+odds)
}
#Store probability
prob <- logit2prob(logit)
prob
}
# Define server to return win probability
server <- function(input, output) {
#Store reactive values
home.pts <- reactive({input$home.pts})
away.pts <- reactive({input$away.pts})
time <- reactive({input$time})
output$win_prob <- renderPrint({win_prob(reactive({input$home.pts}),
reactive({input$away.pts}), reactive({input$time}))})
}
# Run the application
shinyApp(ui = ui, server = server)
如果有人可以帮助我,我将不胜感激!
谢谢!
最佳答案
使用 react 性
server <- function(input, output) {
#Store reactive values
home.pts <- reactive({input$home.pts})
away.pts <- reactive({input$away.pts})
time <- reactive({input$time})
output$win_prob <- renderPrint({win_prob(home.pts(), away.pts(), time())})
}
使用观察事件
server <- function(input, output) {
data <- reactiveValues()
observeEvent(input$goButton,{
data$home.pts <- input$home.pts
data$away.pts <- input$away.pts
data$time <- input$time
})
output$win_prob <- renderPrint({
req(data$home.pts) #to delay displaying result until user press Apply
win_prob(data$home.pts,data$away.pts, data$time)})
}
现在您可以看到两种方法之间的差异
关于从 Shiny 的用户定义函数返回无功输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49948863/