更多查看数据的方法:绘图与下载

案例研究:使用 R 的 Shiny 构建 Web 应用

Dean Attali

Shiny Consultant

绘制数据

  • 探索新数据集常从绘图开始

    • 图是输出
    • UI 中的图输出占位函数:
    plotOutput("my_plot")
    
    • 服务器中的图渲染函数:
  output$my_plot <- renderPlot({
      # code for a plot
  })
案例研究:使用 R 的 Shiny 构建 Web 应用

下载数据

  • 使用下载按钮支持下载

    chapter3_2_more_ways_to_view_data_plot_and_download.009.png

    • 可创建任意类型的下载文件
    • 图像、文本、CSV 等
案例研究:使用 R 的 Shiny 构建 Web 应用

CSV 文件

  • 逗号分隔值(CSV)

  • 存储小到中等规模数据集

  • 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 构建 Web 应用

在 Shiny 中下载数据

  • 下载按钮被视为输出

    • 在 UI 中添加下载按钮(类似输出函数):
    downloadButton(outputId = "download_data", 
                   label = "Download data")
    
    • 在服务器中添加下载处理器(类似渲染函数):
    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 构建 Web 应用

下载处理器

  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 构建 Web 应用

开始练习!

案例研究:使用 R 的 Shiny 构建 Web 应用

Preparing Video For Download...