2017-07-21 18 views
0

私はXMLデータベースで新しくなっています。XMLをデータフレームに構文解析

私は自分の問題を説明しようとします。

分析のためにダウンロードしようとしているメキシコの政府のページのxmlファイルにデータベースが保存されています。

データが見つかるページはこちらです。

https://datos.gob.mx/busca/dataset/estaciones-de-servicio-gasolineras-y-precios-comerciales-de-gasolina-y-diesel

直接ダウンロードリンクは、私が外部リポジトリのようなものであると考え、これです。敬具私は知らない。

https://publicacionexterna.azurewebsites.net/publicaciones/prices

あなたは上記のリンクをクリックすると、XML形式のデータベースが自動的にダウンロードされます。

このデータベースは、小売業者からのメキシコのガス価格で、全国の小数点以下の桁数です。

データベースをダウンロードしてWindowsの.xlsファイルに貼り付けてから、.csvアーカイブを貼り付けて分析用のR環境に移動することができます。

一般的な問題は、ページから私のR環境に直接ダウンロードしようとしているときに、解析を実行できる構造化されたデータベース形式を取得できません。

重複する行が取得されているため、データの各レベルのすべての属性を抽出できません。

これは私の自己で書くことができ、インターネットでヘルプを探していたスクリプトです。

# CRE FILES 

library(easypackages) 

my_packages <- c("rlist","readr", "tidyverse", "lubridate", "stringr", 
"rebus", "stringi", "purrr", "geosphere", "XML", "RCurl", "plyr") 

libraries(my_packages) 

# Link de descarga de documentos 

link1 <-(https://publicacionexterna.azurewebsites.net/publicaciones/prices") 

# First we load the xml file to the enviroment 

data_prices <- getURL(link1) 

xmlfile <- xmlParse(data_prices) 

class(xmlfile) 

xmltop <- xmlRoot(xmlfile) 

base <- ldply(xmlToList(xmltop),data.frame) 

問題は、日付を行ではなく別の列として欲しいということです。あなたの答えをありがとう。

+0

あなたが働いて、最小限のRコード – hrbrmstr

+0

申し訳ありませんああ、私は私がつけたコードで十分だと思った投稿場合は、おそらくより多くの助けを得る、私が説明する方法がわからないと思いますが、私はしようとするだろう。 –

答えて

0

このようなことは、別々の列にあるすべてのデータを含むデータフレームを取得する必要があります。

library(RCurl) 
library(XML) 

# Set link to website 
link1 <-("https://publicacionexterna.azurewebsites.net/publicaciones/prices") 

# Get data from webpage 
data_prices <- getURL(link1) 

# Parse XML data 
xmlfile <- xmlParse(data_prices) 

# Get place nodes 
places <- getNodeSet(xmlfile, "//place") 

# Get values for each place 
values <- lapply(places, function(x){ 
          # Get current place id 
          pid <- xmlAttrs(x) 

          # Get values for each gas type for current place 
          newrows <- lapply(xmlChildren(x), function(y){ 
                   # Get type and update time values 
                   attrs <- xmlAttrs(y) 

                   # Get price value 
                   price <- xmlValue(y) 
                   names(price) <- "price" 

                   # Return values 
                   return(c(pid, attrs, price)) 
                  }) 
          # Combine rows to single list 
          newrows <- do.call(rbind, newrows) 

          # Return rows 
          return(newrows) 
         }) 

# Combine all values into a single dataframe 
df <- as.data.frame(do.call(rbind, values), stringsAsFactors = FALSE) 

# Reset row names for dataframe 
row.names(df) <- c(1:nrow(df)) 
+0

それは単に驚くべきことでしたが、私は一昨日、それを正確にやろうとしていました。このトピックに関するチュートリアルや勧告がある場合。大変ありがとう@Matt。これは素晴らしい答えでした。 –