2012-10-06 8 views
7

내가 자주 EUROSTAT의 데이터를 사용하고 꽤 성가신 나는 EUROSTAT http://epp.eurostat.ec.europa.eu/NavTree_prod/everybody/BulkDownloadListing?sort=1&dir=dic%2FenEUROSTAT에서 R로 데이터를 가져 오는 솔루션입니까?

에서 일괄 다운로드 기능이 제공하는 모든 데이터 세트를 얻기 위해이 조각을 쓴 데이터가 R.로 바로 전방으로로드 할 수 없음을 발견 거기 더 좋은 방법? 하나는 나를 위해 일한 ..이 :

#this library is used to download data from eurostat and to find datasets 
#later extend to extend to find datasets with certain dimensions 

#download data from eurostat 
#unpack and convert to dataframe 
#load label descriptions 
#load factors 
#save as r data object 

datasetname="ebd_all" 

LANGUAGE="en" 

install.packages("RCurl") 
library(RCurl) 
library(data.table) 
library(reshape) 
library(stringr) 

baseurl="http://epp.eurostat.ec.europa.eu/NavTree_prod/everybody/BulkDownloadListing?sort=1&file=data%2F" 

fullfilename=paste(datasetname,".tsv.gz",sep="") 
temp <- paste(tempfile(),".gz",sep="") 
download.file(paste(baseurl,fullfilename,sep=""),temp) 
dataconnection <- gzfile(temp) 
d=read.delim(dataconnection) 
longdata=melt(d,id=colnames(d)[1]) 

firstname=colnames(d)[1] # remove .time and count how many headings are there 
firstname=substr(firstname,1,nchar(firstname)-nchar(".time")) 
headings=toupper(strsplit(firstname,".",fixed=TRUE)[[1]]) 
headingcount=length(headings) 
colnames(longdata)=c("dimensions","time","value") 


#get the data on the dimension tables 
df=data.frame(dimensions=as.character(longdata[,"dimensions"])) 
df = transform(df, dimensions= colsplit(dimensions, split = "\\,",names=headings)) 
dimensions=data.table(df$dimensions) 

#download the dimension labels - save headings as better variable 
dimfile=paste("http://epp.eurostat.ec.europa.eu/NavTree_prod/everybody/BulkDownloadListing?sort=1&file=dic%2F",LANGUAGE,"%2Fdimlst.dic",sep="") 

temp <- paste(tempfile(),".gz",sep="") 
download.file(dimfile,temp) 
dataconnection <- gzfile(temp) 
dimdata=read.delim(dataconnection,header=FALSE) 
colnames(dimdata)=c("colname","desc") 
lab=dimdata$desc 
names(lab)=dimdata$colname 

#create headings that speak for themselves for columns 
speakingheadings=as.character(lab[headings]) 

#download factors for each heading and add 
for(heading in headings){ 
    factorfile=paste("http://epp.eurostat.ec.europa.eu/NavTree_prod/everybody/BulkDownloadListing?sort=1&file=dic%2F",LANGUAGE,"%2F",tolower(heading),".dic",sep="") 
    temp <- paste(tempfile(),".gz",sep="") 
    download.file(factorfile,temp) 
    dataconnection <- gzfile(temp) 
    factordata=read.delim(dataconnection,header=FALSE) 
    colnames(factordata)=c(heading,paste(heading,"_desc",sep="")) 
    #join the heading to the heading dataset 
    dimensions=merge(dimensions,factordata,by=heading,all.x=TRUE) 
} 


    #at the end at speaking headings 
setnames(dimensions,colnames(dimensions)[1:length(speakingheadings)],speakingheadings) 

    #add data columns by writing and reading again---FASTER ;-) 
temp=tempfile() 
values=data.frame(value=as.character(longdata$value)) 
values = transform(values, value= colsplit(value, split = "\\ ",names=c("value","flag"))) 
values=values$value 
values=data.table(values) 

values$value=as.character(values$value) 
values$flag=as.character(values$flag) 
values[value==flag,flag:=NA] 
values$value=as.double(values$value) 

eurostatdata=cbind(dimensions,time=longdata$time,values) 
save(eurostatdata,file=paste(datasetname,".RData")) 
+0

[eurostat] (https://cran.r-project.org/web/packages/eurostat/index.html)라는 R 패키지가 2015 년에 출시되었습니다. 멋진 [vignette] (https : // github. co.kr/rOpenGov/eurostat/blob/master/vignettes/2015-RJournal/lahti-huovari-kainu-biecek.md)에서는 eurostat 데이터를 다운로드하고 시각화하기위한 예제 지침을 제공합니다. 아래에 언급 된 [SmarterPoland] (https://cran.r-project.org/web/packages/SmarterPoland/index.html) 패키지의 저자는 eurostat 패키지의 공동 저자 중 한 명입니다. –

답변

7

체크 아웃 SmarterPoland 패키지를 다운로드 (및 R에 들어가) EUROSTAT에서 직접 데이터를하는 기능이있다. 여기

예이다

library(SmarterPoland) 
# info about passagers 
grepEurostatTOC("split of passenger transport") 
## get table 
tmp <- getEurostatRCV("tsdtr210") 
summary(tmp) 

##  vehicle   geo   time   value  
## BUS_TOT:756 AT  : 63 1990 : 108 Min. : 0.0 
## CAR :756 BE  : 63 1991 : 108 1st Qu.: 6.9 
## TRN :756 BG  : 63 1992 : 108 Median :12.9 
##    CH  : 63 1993 : 108 Mean :33.6 
##    CY  : 63 1994 : 108 3rd Qu.:77.4 
##    CZ  : 63 1995 : 108 Max. :93.4 
##    (Other):1890 (Other):1620 NA's :397 

소스 : www.smarterpoland.pl

+0

eurostat R 패키지는 SmarterPoland를 기반으로 개발되었으며 동일한 원본 저자를 포함합니다. eurostat R 패키지의 eurostat 특정 도구는 이제 SmarterPoland에있는 것보다 최신이고 유지 관리가 잘됩니다 (패키지에 다른 유용한 기능이 포함될 수 있음). – antagomir

2

개정 답변자 RJSDMX package도 R. 예에 유로 스타트로부터 데이터를 검색하는데 사용될 수있다

아래에 나와 있습니다.

library(RJSDMX) 
data <- getTimeSeries("EUROSTAT","nama_gdp_c/.EUR_HAB.B1GM.DE") 

(참조 여기 왼쪽) 초기 응답

더 좋은 방법은 통계청 (Eurostat) 데이터에 프로그래밍 방식으로 액세스를 제공하는 Eurostat Web Service facility를 사용하는 수 있습니다. 웹 서비스 기능은 Eurostat에서 데이터베이스에서 데이터를 추출하기 위해 제공하는 대량 다운로드 기능 외에도 또 다른 서비스입니다. 서비스를 사용하려면 REST 또는 SOAP 요청을 보내야합니다. 서버에서 검색된 데이터는 XML 패키지를 사용하여 구문 분석 할 수있는 XML 문서 유형 인 계층 적 데이터 구조입니다. 참고로 http://epp.eurostat.ec.europa.eu/portal/page/portal/sdmx_web_services/getting_started/a_few_useful_points

# Step 0: Load the XML package. 
# This is used later on to parse the XML retrieved from Eurostat. 
# For a tutorial on XML and parsing XML documents, read this: http://www.w3schools.com/xpath/default.asp 

library(XML) 

# Step 1: Construct the appropriate REST query. 
# First read this:  http://epp.eurostat.ec.europa.eu/portal/page/portal/sdmx_web_services/getting_started/a_few_useful_points 

# Specify the data to be retrieved. 

resource <- "data" 
dataflow <- "nama_gdp_c" 
key   <- ".EUR_HAB.B1GM.DE" 
time_filter <- "?startPeriod=2010" 

# Construct the query 

partial_url <- paste(paste(resource, dataflow, key, sep="/"), time_filter, sep="") 
base_url <- "http://ec.europa.eu/eurostat/SDMX/diss-web/rest/" 
rest_query <- paste(base_url, partial_url, sep="") 

# Step 2: Make the request using cURL (that is, retrieve the data) 
# For information about cURL, read this: http://curl.haxx.se/ 
# For information about the curl command, check out the man pages: http://curl.haxx.se/docs/manpage.html 

command <- paste("curl", rest_query) 
raw_data <- system(command, intern=TRUE) 

# Note: at this stage, the data is a character object. 

class(raw_data) 

# View the data, which can be found commented out at the bottom of this script. Note that it is a hierarchical data structure. 

# Step 3: Parse the data 
# Here we use functions from the XML package - one could, of course, use base package functions, but why? 

data <- xmlParse(raw_data) 

# Parsing the data returns an object of class: "XMLInternalDocument" and "XMLAbstractDocument" 

class(data) 

# Step 4: Extract the numerical data 

# Data can be found using getNodeSet(), but the data remains stuck between "tags" - we just want the numbers. 

getNodeSet(data,"//generic:ObsValue") 

# The numbers we want to extract are, in this case, value "attributes". We can target these values as follows. 

xpathApply(data, "//generic:ObsValue", xmlGetAttr, name="value") 

# That does the job, but really we'd like those numbers in a vector rather than a list object. 

numbers <- as.numeric(xpathApply(data, "//generic:ObsValue", xmlGetAttr, name="value")) 

# Step 5: Extract the dates (years) - i.e. get some metadata. 
# This is similar to above. 

years <- as.numeric(xpathApply(data, "//generic:ObsDimension", xmlGetAttr, name="value")) 

# Step 6 and on-wards: 
# 
# Enter your code here... =) 
# 
# 
# 

는, 원시 데이터는 다음과 같습니다

아래의 간단한 예제를 체크 아웃하기 전에, 나는 여기에서 찾을 수 있습니다 Eurotat 제공하는 서비스에 대한 정보의 일부를 읽고 추천 : 내가 요청을 보낼 컬을 사용했지만, 이것은 많은 다른 방법으로, 예에서 수행 될 수 있었다 :

<?xml version="1.0" encoding="utf-8"?> 
<message:GenericData xmlns:footer="http://www.sdmx.org/resources/sdmxml/schemas/v2_1/message/footer" xmlns:generic="http://www.sdmx.org/resources/sdmxml/schemas/v2_1/data/generic" xmlns:common="http://www.sdmx.org/resources/sdmxml/schemas/v2_1/common" xmlns:message="http://www.sdmx.org/resources/sdmxml/schemas/v2_1/message" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <message:Header> 
    <message:ID>13e08b8d24936d75b3a6fa1b9c632e22</message:ID> 
    <message:Test>false</message:Test> 
    <message:Prepared>2014-10-20T21:10:50</message:Prepared> 
    <message:Sender id="ESTAT"> 
     <common:Name xml:lang="en">Eurostat</common:Name> 
     <message:Timezone>+01:00</message:Timezone> 
    </message:Sender> 
    <message:Receiver id="RECEIVER"/> 
    <message:Structure structureID="ESTAT_DSD_nama_gdp_c_1_0" dimensionAtObservation="TIME_PERIOD"> 
     <common:Structure> 
     <Ref agencyID="ESTAT" id="DSD_nama_gdp_c" version="1.0"/> 
     </common:Structure> 
    </message:Structure> 
    <message:DataSetAction>Append</message:DataSetAction> 
    <message:DataSetID>nama_gdp_c</message:DataSetID> 
    </message:Header> 
    <message:DataSet structureRef="ESTAT_DSD_nama_gdp_c_1_0"> 
    <generic:Series> 
     <generic:SeriesKey> 
     <generic:Value id="UNIT" value="EUR_HAB"/> 
     <generic:Value id="INDIC_NA" value="B1GM"/> 
     <generic:Value id="GEO" value="DE"/> 
     <generic:Value id="FREQ" value="A"/> 
     </generic:SeriesKey> 
     <generic:Obs> 
     <generic:ObsDimension value="2013"/> 
     <generic:ObsValue value="33300.0"/> 
     </generic:Obs> 
     <generic:Obs> 
     <generic:ObsDimension value="2012"/> 
     <generic:ObsValue value="32600.0"/> 
     </generic:Obs> 
     <generic:Obs> 
     <generic:ObsDimension value="2011"/> 
     <generic:ObsValue value="31900.0"/> 
     </generic:Obs> 
     <generic:Obs> 
     <generic:ObsDimension value="2010"/> 
     <generic:ObsValue value="30500.0"/> 
     </generic:Obs> 
    </generic:Series> 
    </message:DataSet> 
</message:GenericData> 

참고할 사항 Wget, Perl, PHP 등을 사용합니다. system() 명령을 사용하고자한다면, 프로그램 방식으로 Eurostat에서 R로 데이터를 가져 오는 것은 간단합니다 (아래 편집 참조). 데이터를 말하자면 ts 객체 (또는 사용자가 보낸 질의에 따라 mts 객체)로 변환하는 것은 너무 직설적이어야합니다. 마지막으로 Linux 운영 체제 (Ubuntu 배포판)를 사용하고 있으므로 Windows를 사용하는 경우 위의 예가 도움이되지 않을 수 있습니다.

도움이 되었기를 바랍니다.

편집 : 방금 RCurl 패키지를로드 한 것으로 나타났습니다. 원하는 경우 패키지가 제공 한 기능을 내가 사용한 시스템 명령으로 바꿀 수 있습니다.

6

Eurostat은 통계 데이터를 SDMX 형식으로 보급합니다. R에서는 rsdmx 패키지를 사용하여 데이터를 읽을 수 있습니다.

#in case you want to install rsdmx from Github 
#(otherwise you can install it from CRAN) 
require(devtools) 
install_github("rsdmx", "opensdmx") 
require(rsdmx) 

#read EUROSTAT dataset 
dataURL <- "http://ec.europa.eu/eurostat/SDMX/diss-web/rest/data/cdh_e_fos/..PC.FOS1.BE/?startperiod=2005&endPeriod=2011 " 
sdmx <- readSDMX(dataURL) 
stats <- as.data.frame(sdmx) 
head(stats) 

참고 : 예를 들어 아래를 참조하십시오 당신이 중 하나 CRAN에서 rsdmx 찾거나 GitHub의 저장소에서 직접 설치할 수 있습니다. https://github.com/opensdmx/rsdmx

rsdmx는 SDMX datasets하지만 모든 SDMX 문서, data structurescodelists를 포함하는 데이터 또는 메타 데이터를 읽기에 한정되는 것은 아니다. 더 많은 예제가 필요하면 rsdmx wiki을 확인해 주시기 바랍니다.

+1

+1 내가 제안한 방법보다 단순하고 R 사용자 친화적 인 접근 방식처럼 보입니다. 여기서 R 사용자는 XPath를 직접 사용할 필요가 없으므로 참으로 훌륭한 작업입니다. 앞으로 rsdmx 사용을 기대합니다. –

+1

감사합니다. Graeme Walsh! 네, [rsdmx] (https://github.com/opensdmx/rsdmx)의 목적 중 하나는 가능한 한 간단하게 만드는 것입니다. 결과적으로 최종 사용자를위한''readSDMX''라는 독특한 함수가 생깁니다. 이 함수는 올바른 SDMX R 객체를 인스턴스화합니다. 파싱 ​​접근법은 XPath이지만, 나중에 거대한 데이터 세트를 위해 SAX와 같은 다른 접근법으로 확장 될 예정입니다. EUROSTAT는''rsdmx ''를 사용할 수있는 소스 중 하나이지만 다른 것들에 대해서도 테스트를 마쳤습니다. OECD, ECB, FAO. – eblondel

+1

Eblondel, 나는 당신의 접근 방식을 매우 간단하고 효율적으로 생각합니다. Eurostat 웹 사이트에서 제공되는 SDMX 문서를 읽었으나 원하는 URL을 효율적으로 생성 할 수있는 방법이 있는지 궁금합니다. 이상적으로는, 모든 시계열에 대해 실업률이있는 NUT3 수준 테이블을 생성하는 dataURL을 생성하고 싶습니다. 어떻게 Eurostat 웹 사이트를 사용하여 URL에 필요한 모든 요소를 ​​찾을 수 있습니까? – Konrad

관련 문제