更直接的方法从XML文件创建数据帧列表?

时间:2014-07-24 08:47:51

标签: xml r xpath lapply

SDMX(统计数据和元数据交换)是一个&#39; XML&#39;定义交换统计数据标准的语法。它使用称为数据集结构定义描述(DSD)的文件来传达数据集的结构。除此之外,DSD还包含一个节点Codelists,该节点由Codelist项组成,而Code项又是Namelibrary(XML);library(RCurl) # REST resource for DSD of nama_gdp_c # downloading, parsing XML an setting root file <- "http://ec.europa.eu/eurostat/SDMX/diss-web/rest/datastructure/ESTAT/DSD_nama_gdp_c" content <- getURL(file, httpheader = list('User-Agent' = 'R-Agent')) root <- xmlRoot(xmlInternalTreeParse(content, useInternalNodes = TRUE)) # get Nodeset of Codelists and its length nodes <- getNodeSet(root,"//str:Codelist") nn <- length(nodes) # Create nested List of all Codes and Names codelistAll <- lapply(seq(nn),function(i){ xpathSApply(root,paste0("//str:Codelist[",i,"]/str:Code"),xmlGetAttr, "id") }) namelistAll <- lapply(seq(nn),function(i){ xpathSApply(root,paste0("//str:Codelist[",i,"]/str:Code/com:Name"),xmlValue) }) # Create a list of dataframes from the nested lists alldfList <-lapply(seq(nn),function(i) data.frame(codes=codelistAll[[i]],names=namelistAll[[i]])) # Name the list items like the nodes names(alldfList) <- sapply(nodes, xmlGetAttr,"id") 项和attribuet的父项。我目前正在尝试使用以下代码将Eurostats REST interface中请求的DSD文件的这些代码列表解析为R中的数据帧列表:

alldfList

这会产生> str(alldfList) List of 6 $ CL_FREQ :'data.frame': 6 obs. of 2 variables: ..$ codes: Factor w/ 6 levels "A","D","H","M",..: 2 6 5 1 4 3 ..$ names: Factor w/ 6 levels "Annual","Daily",..: 2 6 4 1 3 5 $ CL_GEO :'data.frame': 49 obs. of 2 variables: ..$ codes: Factor w/ 49 levels "AT","BA","BE",..: 22 21 20 10 16 15 14 13 12 11 ... ..$ names: Factor w/ 49 levels "Austria","Belgium",..: 19 18 17 16 15 14 13 12 11 10 ... ,我正在寻找的数据帧列表。

paste0

虽然这样做了,但我觉得必须有一个更直接的语法才能实现这一目标。特别是XML的使用和名称的最终分配似乎很尴尬。我一直在阅读xlmChildren包的文档,我怀疑它必须是{{1}}的一些操作,但我无法理解如何实际操作。有没有人建议采用规范的方式进行此操作?任何建议都将不胜感激。

2 个答案:

答案 0 :(得分:1)

您可以直接从节点获取data.frames,但需要使用命名空间

ns <- c(str="http://www.sdmx.org/resources/sdmxml/schemas/v2_1/structure")

alldfList <- lapply(nodes, function(x){ data.frame(
  codes= xpathSApply(x, ".//str:Code" , xmlGetAttr, "id", namespaces=ns),
  names= xpathSApply(x, ".//str:Code" , xmlValue, namespaces=ns) )})

names(alldfList)  <- sapply(nodes, xmlGetAttr,"id")

答案 1 :(得分:0)

当您尝试读取R中的SDMX-ML文件时,您可以尝试Github中托管的rsdmx包。该软件包可在CRAN下载,最新版本允许您阅读数据结构定义(DSD)和组件,包括代码列表,概念和KeyFamilies。

对于安装,如果您可以使用以下方法轻松地从Github安装它:

require(devtools)
install_github("rsdmx", "opensdmx")

以代码列表为例,您可以轻松地将SDMX代码列表强制转换为data.frame,执行以下操作:

require(rsdmx)
file <- "http://ec.europa.eu/eurostat/SDMX/diss-web/rest/datastructure/ESTAT/DSD_nama_gdp_c"
sdmx <- readSDMX(file)

#get the list of codelist Id
codelists <- sapply(sdmx@codelists, function(x) x@id)

#get some specific codelist as data.frame
codelist <- as.data.frame(sdmx, codelistId = "CL_GEO")
head(codelist)

可以对SDMX Concepts / ConceptSchemes,完整的数据结构定义(DSD)以及确定的SDMX数据集进行类似的操作。在rsdmx wiki查看更多示例。

希望这有帮助!