案例研究:使用 R 的 Shiny 建置網頁應用程式
Dean Attali
Shiny Consultant
data <- gapminder
data <- subset(
data,
lifeExp >= input$life[1] & lifeExp <= input$life[2]
)
if (input$continent != "All") {
data <- subset(
data,
continent == input$continent
)
}
renderTable()renderPlot()downloadHandler()reactive() 變數取代重複程式碼output$my_table <- renderTable({
data <- gapminder
data <- subset(
data,
lifeExp >= input$life[1] & lifeExp <= input$life[2]
)
})
my_data <- reactive({data <- gapminder data <- subset( data, lifeExp >= input$life[1] & lifeExp <= input$life[2] )})output$my_table <- renderTable({ my_data() })
output$table <- renderTable({
fit_model(input$num)
})
output$plot <- renderPlot({
ggplot(
fit_model(input$num), ...)
})
fit_model() 需時 5 秒fit_model() 呼叫兩次 = 10 秒x <- reactive({ fit_model(input$num) })output$table <- renderTable({ x() })output$plot <- renderPlot({ ggplot(x(), ...) })
x() 被呼叫兩次,但 x 內部程式只跑一次fit_model() 只呼叫一次 = 5 秒延遲求值:直到需要時才計算
x <- reactive({
fit_model(input*num)
})
output$download <- downloadHandler(
filename = "x.csv",
content = function(file) {
write.csv(x(), file)
}
)
只有請求下載時才會執行 x(),而非每次 input$num 改變都執行
案例研究:使用 R 的 Shiny 建置網頁應用程式