更多資料檢視方式:繪圖與下載

案例研究:使用 R 的 Shiny 建置網頁應用程式

Dean Attali

Shiny Consultant

繪製資料

  • 探索新資料集時,繪圖常是第一步

    • 繪圖屬於輸出
    • UI 中的繪圖輸出預留函式:
    plotOutput("my_plot")
    
    • 伺服器中的繪圖 render 函式:
  output$my_plot <- renderPlot({
      # code for a plot
  })
案例研究:使用 R 的 Shiny 建置網頁應用程式

下載資料

  • 下載功能可用下載按鈕完成

    chapter3_2_more_ways_to_view_data_plot_and_download.009.png

    • 可建立任意類型的可下載檔案
    • 圖片檔、文字檔、CSV 檔
案例研究:使用 R 的 Shiny 建置網頁應用程式

CSV 檔案

  • Comma Separated Values(逗號分隔值)

  • 儲存小到中型資料集

  • gapminder 的 CSV:

    country,continent,year,lifeExp,pop,gdpPercap  
    Afghanistan,Asia,1952,28.801,8425333,779.4453145  
    Afghanistan,Asia,1957,30.332,9240934,820.8530296  
    Afghanistan,Asia,1962,31.997,10267083,853.10071  
    Afghanistan,Asia,1967,34.02,11537966,836.1971382
    
  • 建立 CSV 檔:

write.csv(gapminder, "myfile.csv")
案例研究:使用 R 的 Shiny 建置網頁應用程式

在 Shiny 中下載資料

  • 下載按鈕視為輸出

    • 在 UI 加入下載按鈕:(類似輸出函式)
    downloadButton(outputId = "download_data", 
                   label = "Download data")
    
    • 在伺服器加入下載處理器:(類似 render 函式)
    output$download_data <- downloadHandler(
        filename = "data.csv",
        content = function(file) {
            # Code that creates a file in the path <file>
            write.csv(gapminder, file)
        }
    )
    
案例研究:使用 R 的 Shiny 建置網頁應用程式

下載處理器

  output$download_data <- downloadHandler(
      filename = "data.csv",
      content = function(file) {
          # code that creates a file in the path <file>
          write.csv(gapminder, file)
      }
  )
  • downloadHandler() 有兩個引數
    • filename
      • 下載檔案名稱
    • content(file)
      • 帶 1 個引數的函式
      • 建立要下載的檔案,引數是檔案路徑
案例研究:使用 R 的 Shiny 建置網頁應用程式

一起來練習吧!

案例研究:使用 R 的 Shiny 建置網頁應用程式

Preparing Video For Download...