首页 > 解决方案 > 使用 HTTR GET 请求从 github 下载 .csv 文件

问题描述

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

这是我要下载的表格。

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 上的表格的数据框。

任何帮助将不胜感激。

标签: gethttr

解决方案


我是 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))]

输出图

我是如何让它工作的:


推荐阅读