Skip to content

Instantly share code, notes, and snippets.

@jcheng5
Created July 5, 2019 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcheng5/6147c1d8beabaea4aea2462f83262208 to your computer and use it in GitHub Desktop.
Save jcheng5/6147c1d8beabaea4aea2462f83262208 to your computer and use it in GitHub Desktop.
Celsius <=> Fahrenheit
library(shiny)
ui <- fluidPage(
numericInput("temp_c", "Celsius", NA),
numericInput("temp_f", "Fahrenheit", NA)
)
server <- function(input, output, session) {
c_to_f <- function(c, decimals = 1) {
round((c * 9 / 5) + 32, decimals)
}
f_to_c <- function(f, decimals = 1) {
round((f - 32) * 5 / 9, decimals)
}
observeEvent(input$temp_c, {
# This early return is to prevent event handler cycles.
# For example, setting F to 40 sets C to 4.4, which sets F to 39.9.
# The conditional here is a crude way to prevent that 39.9.
if (isTRUE(input$temp_c == f_to_c(input$temp_f))) {
return()
}
updateNumericInput(session, "temp_f",
value = c_to_f(input$temp_c))
})
observeEvent(input$temp_f, {
if (isTRUE(input$temp_f == c_to_f(input$temp_c))) {
return()
}
updateNumericInput(session, "temp_c",
value = f_to_c(input$temp_f))
})
}
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment