forked from ropensci-archive/convertr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gadget.R
116 lines (94 loc) · 3.22 KB
/
gadget.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#' Launch interactive conversion gadget
#'
#' @param vector
#' A numeric vector to convert. You can change the vector within the app.
#'
#' @return
#' Insert text into code with a proper convertr::convert() call.
#' @export
#'
convert_gadget <- function(vector) {
si_units <- unique(conversion_table$base_unit[conversion_table$multi_unit])
si_units <- si_units[order(si_units)]
if(missing(vector)){
express <- "1:10"
} else {
express <- deparse(substitute(vector))
}
ui <- miniUI::miniPage(
miniUI::gadgetTitleBar("Unit Converter"),
miniUI::miniContentPanel(
shiny::fluidRow(
shiny::selectInput("si_unit",
"SI Unit",
c("All", si_units)),
shiny::textInput("vector", "Epression Returning Numeric Vector",
express)
),
shiny::fluidRow(
shiny::column(width = 6,
shiny::uiOutput("from_unit")
),
shiny::column( width = 6,
shiny::uiOutput("to_unit")
)
),
shiny::fluidRow(
DT::dataTableOutput("table", width = "75%")
)
)
)
server <- function(input, output, session) {
vector <- shiny::reactive(eval(parse( text = input$vector)))
output$from_unit <- shiny::renderUI({
if(input$si_unit == "All"){
return(
shiny::selectInput("from_unit", "From Unit",
unique(conversion_table$catalog_symbol))
)
} else {
choices <- conversion_table[conversion_table$base_unit ==
input$si_unit, "catalog_symbol"]
shiny::selectInput("from_unit", "From Unit", unique(choices))
}
})
output$to_unit <- shiny::renderUI({
if(input$si_unit == "All"){
shiny::selectInput("to_unit", "To Unit",
unique(conversion_table$catalog_symbol))
} else {
choices <- conversion_table[conversion_table$base_unit ==
input$si_unit, "catalog_symbol"]
shiny::selectInput("to_unit", "To Unit", unique(choices))
}
})
output$table <- DT::renderDataTable({
req(input$from_unit, input$to_unit)
if(is.numeric(vector())){
v1 <- vector()[1:min(length(vector()), 20)]
} else{
v1 <- 1:10
}
v2 <- convert(v1, input$from_unit, input$to_unit)
out <- data.frame(From = v1, To = v2)
names(out) <- c(conversion_table[conversion_table$catalog_symbol ==
input$from_unit, "name"],
conversion_table[conversion_table$catalog_symbol ==
input$to_unit, "name"])
out
}, options = list(searching = FALSE, paging = FALSE),
rownames = FALSE)
# When the Done button is clicked, return a value
shiny::observeEvent(input$done, {
code <- paste0("convertr::convert(",
input$vector,
",'",
input$from_unit,
"','",
input$to_unit,
"')")
shiny::stopApp(rstudioapi::insertText(code))
})
}
shiny::runGadget(ui, server)
}