Created
July 5, 2019 15:35
-
-
Save jcheng5/6147c1d8beabaea4aea2462f83262208 to your computer and use it in GitHub Desktop.
Celsius <=> Fahrenheit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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