forked from blairj09-talks/bmdd-plumber
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathapp.R
101 lines (84 loc) · 3.11 KB
/
app.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# API app -----------------------------------------------------------------
# Shiny App for providing data input to cars plumber API
library(shiny)
library(httr)
base_url <- config::get("base_url")
ui <- fluidPage(
# Application title
titlePanel("Cars MPG Predictor"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("hp",
"Horsepower",
min = min(mtcars$hp),
max = max(mtcars$hp),
value = median(mtcars$hp)),
selectInput("cyl",
"Cylinder",
choices = sort(unique(mtcars$cyl)),
selected = sort(unique(mtcars$cyl))[1]),
fluidRow(
actionButton("add",
"Add"),
actionButton("remove",
"Remove"),
actionButton("predict",
"Predict")
)
),
# Show a plot of the generated distribution
mainPanel(
tableOutput("data"),
wellPanel(
textOutput("raw_results")
)
)
)
)
server <- function(input, output) {
# Create reactive_values
reactive_values <- reactiveValues(data = data.frame(),
predicted_values = NULL)
# Update user data
observeEvent(input$add, {
# Reset predicted_values
reactive_values$predicted_values <- NULL
# Add to data
data <- reactive_values$data
# Remove predicted column if present
reactive_values$data <- rbind(data[!names(data) %in% "predicted_mpg"],
data.frame(hp = as.numeric(input$hp), cyl = as.numeric(input$cyl)))
})
observeEvent(input$remove, {
# Reset predicted_values
reactive_values$predicted_values <- NULL
# Set aside existing data
data <- reactive_values$data
# Remove rows that match current input
reactive_values$data <- dplyr::anti_join(data[!names(data) %in% "predicted_mpg"],
data.frame(hp = as.numeric(input$hp), cyl = as.numeric(input$cyl)))
})
observeEvent(input$predict, {
# Make API request
api_res <- httr::POST(url = paste0(base_url, "/predict"),
body = reactive_values$data,
encode = "json")
# Extract JSON from API response
reactive_values$predicted_values <- httr::content(api_res, as = "text", encoding = "UTF-8")
# Add predicted values to data
if (!"predicted_mpg" %in% names(reactive_values$data)) {
reactive_values$data <- cbind(reactive_values$data,
predicted_mpg = as.numeric(jsonlite::fromJSON(reactive_values$predicted_values)))
}
})
output$data <- renderTable(reactive_values$data)
output$raw_results <- renderPrint({
if (is.null(reactive_values$predicted_values)) {
"No predictions"
} else {
jsonlite::prettify(reactive_values$predicted_values)
}
})
}
shinyApp(ui = ui, server = server)