1

我正在尝试将此xml_file(以及许多其他类似文件)转换为 R 中的 data.frame。期望的结果:具有以下内容的 data.frame(或 tibble、data.table 等):

  • 每行Deputado(这是 的主要标签/级别xml_file,其中有 4 个)
  • 每个 Deputado 中的所有变量都应该是列。
  • 可以忽略具有多个值的嵌套类别(例如comissao、等)。cargoComissoes

在下面的代码中,我尝试密切关注github/.../xmltools 的自述文件中的示例 2,但出现错误:

...
+   dplyr::mutate_all(empty_as_na)
Error: Argument 4 must be length 4, not 39

任何解决此问题的帮助(或完整示例的不同策略)将不胜感激。

代码(具有可重现的错误)是:

file <- "https://www.camara.leg.br/SitCamaraWS/Deputados.asmx/ObterDetalhesDeputado?ideCadastro=141428&numLegislatura="
doc <- file %>%
  xml2::read_xml()
nodeset <- doc %>%
  xml2::xml_children()
length(nodeset) # lots of nodes!
nodeset[1] %>% # lets look at ONE node's tree
  xml_view_tree()
# lets assume that most nodes share the same structure
terminal_paths <- nodeset[1] %>%
  xml_get_paths(only_terminal_parent = TRUE)

terminal_xpaths <- terminal_paths %>% ## collapse xpaths to unique only
  unlist() %>%
  unique()

# xml_to_df (XML package based)
## note that we use file, not doc, hence is_xml = FALSE
# df1 <- lapply(xpaths, xml_to_df, file = file, is_xml = FALSE, dig = FALSE) %>%
#   dplyr::bind_cols()
# df1

# xml_dig_df (xml2 package based)
## faster!
empty_as_na <- function(x){
  if("factor" %in% class(x)) x <- as.character(x) ## since ifelse wont work with factors
  if(class(x) == "character") ifelse(as.character(x)!="", x, NA) else x
}

terminal_nodesets <- lapply(terminal_xpaths, xml2::xml_find_all, x = doc) # use xml docs, not nodesets! I think this is because it searches the 'root'.
df2 <- terminal_nodesets %>%
  purrr::map(xml_dig_df) %>%
  purrr::map(dplyr::bind_rows) %>%
  dplyr::bind_cols() %>%
  dplyr::mutate_all(empty_as_na)
4

1 回答 1

1

这是一种使用 XML 包的方法。

library(tidyverse)
library(XML)

df = xmlInternalTreeParse("./Data/ObterDetalhesDeputado.xml")
df_root = xmlRoot(df)
df_children = xmlChildren(df_root)

df_flattened = map_dfr(df_children,  ~.x %>% 
                         xmlToList() %>% 
                         unlist %>% 
                         stack %>% 
                         mutate(ind = as.character(ind),
                                ind = make.unique(ind)) %>% # for duplicate identifiers
                         spread(ind, values))

以下节点是嵌套列表。因此它们将显示为附有数字的重复列。您可以相应地删除它们。

cargosComissoes 2
partidoAtual 3
gabinete 3
historicoLider 4
comissoes 11
于 2019-06-10T06:54:03.523 回答