【问题标题】:Download .csv file from github using HTTR GET request使用 HTTR GET 请求从 github 下载 .csv 文件
【发布时间】:2020-03-16 22:37:25
【问题描述】:

我正在尝试使用 HTTR 包中的 GET 函数在 R 中创建自动拉取位于 github 上的 csv 文件。

这是我要下载的表格。

https://github.com/CSSEGISandData/COVID-19/blob/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv

我可以使用以下 GET 请求连接到文件:

library(httr)

x <- httr::GET("https://github.com/CSSEGISandData/COVID-19/blob/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv")

但是我不确定如何将其转换为类似于 github 上的表格的数据框。

任何帮助将不胜感激。

【问题讨论】:

    标签: get httr


    【解决方案1】:

    我是 R 新手,但这是我的解决方案。

    您需要使用来自 github (raw.githubusercontent.com) 的原始版本的 csv 文件!

    library(httr)
    
    x <- httr::GET("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv")
    
    # Save to file
    bin <- content(x, "raw")
    writeBin(bin, "data.csv")
    
    # Read as csv
    dat = read.csv("data.csv", header = TRUE, dec = ",")
    
    colnames(dat) = gsub("X", "", colnames(dat))
    
    # Group by country name (to sum regions)
    # Skip the four first columns containing metadata 
    countries = aggregate(dat[, 5:ncol(dat)], by=list(Country.Region=dat$Country.Region), FUN=sum)
    
    # Here is the table of the most recent total confirmed cases
    countries_total = countries[, c(1, ncol(countries))]
    

    The output graph

    我是如何做到这一点的:

    【讨论】:

      【解决方案2】:

      这很简单:

      res <- httr::GET("https://.../file.csv")
      data <- httr::content(res, "parsed")
      

      这需要readr 包。

      https://httr.r-lib.org/reference/content.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多