2017-07-21 118 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。這是一個很好的答案。 –