繁体   English   中英

使用R下载压缩数据文件,解压缩并导入.csv

[英]Using R to download zipped data file, extract, and import .csv

我正在尝试使用R从网页下载并提取.csv文件。

此问题与使用R下载压缩数据文件,提取和导入数据重复。

我无法使解决方案工作,但可能是由于我正在使用的网址。

我试图从http://data.worldbank.org/country/united-kingdom下载.csv文件(在下载数据下拉列表下)

使用上面链接中的@Dirk解决方案,我试过了

temp <- tempfile()
download.file("http://api.worldbank.org/v2/en/country/gbr?downloadformat=csv",temp)
con <- unz(temp, "gbr_Country_en_csv_v2.csv")
dat <- read.table(con, header=T, skip=2)
unlink(temp)

我通过查看页面源代码获得了扩展链接,我期望它会导致问题,尽管如果我将其粘贴到地址栏中它会起作用。

该文件使用正确的Gb下载

download.file("http://api.worldbank.org/v2/en/country/gbr?downloadformat=csv",temp)
# trying URL 'http://api.worldbank.org/v2/en/country/gbr?downloadformat=csv'
# Content type 'application/zip' length 332358 bytes (324 Kb)
# opened URL
# downloaded 324 Kb

# also tried unzip but get this warning
con <- unzip(temp, "gbr_Country_en_csv_v2.csv")
# Warning message:
# In unzip(temp, "gbr_Country_en_csv_v2.csv") :
# requested file not found in the zip file

但是当我手动下载它们时,这些是文件名。

谢谢你,我会感谢你在哪里出错了

我使用的是Windows 8,R 3.1.0版

为了让您的数据下载和解压缩,您需要设置mode="wb"

download.file("...",temp, mode="wb")
unzip(temp, "gbr_Country_en_csv_v2.csv")
dd <- read.table("gbr_Country_en_csv_v2.csv", sep=",",skip=2, header=T)

看起来默认为“w”,它假定文本文件。 如果它是一个简单的csv文件,这没关系。 但由于它是压缩的,它是一个二进制文件,因此是“wb”。 如果没有“wb”部分,则根本无法打开拉链。

这几乎一切都好。 在这种情况下,您只需要指定它是逗号分隔文件,例如在read.table使用sep=","

temp <- tempfile()
download.file("http://api.worldbank.org/v2/en/country/gbr?downloadformat=csv", 
              temp)
con <- unz(temp, "gbr_Country_en_csv_v2.csv")
dat <- read.table(con, header=T, skip=2, sep=",")
unlink(temp)

通过这个小小的改变,我可以顺利导入你的csv。

HTH,Luca

可以使用WDI软件包获得Word Bank Developmet Indictors。 例如,

library(WDI)
inds <- WDIsearch(field = "indicator")[, 1]
GB <- WDI("GB", indicator = inds)

有关详细信息,请参阅WDIsearchWDI函数以及重新参考手册

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM