XML 个文件到数据框
XML files to dataframe
我想阅读 XML 860 个文件。
所有 xml 个文件都具有
结构
<ip id_pac="48">
<rodcis>48</rodcis>
<jmeno>Andrew</jmeno>
<prijmeni>Mazal</prijmeni>
<titul_pred></titul_pred>
<titul_za></titul_za>
<dat_dn format="D">1999-06-21</dat_dn>
<dat_de format="D"></dat_de>
<sex>M</sex>
<rod_prijm></rod_prijm>
<a typ="1">
<dat_od format="D">2020-09-17</dat_od>
</a>
</ip>
我想获取其中一列为“rodcis”(在本例中为 48)和第二列为“dat_od”(在本例中为 2020-09-17)的数据框
我正在尝试这个
- 获取所有 XML 个文件
files <- list.files(path = "~/Downloads/XML",
pattern = "*.xml",
full.names = TRUE)
- 获取包含所有 860 XML 个文件的列表(输出)
out <- lapply(files, xmlParse)
- 列表到数据框
dataframe <- do.call(rbind, lapply(out, function(x) rootnode[[1]][[2]], rootnode[[2]][[1]]))
但是出现了一个我不明白的错误。
cannot coerce type 'externalptr' to vector of type 'list'
这是使用 xml2 包的可能解决方案。有关分步指南,请参阅代码中的注释。
library(xml2)
library(dplyr)
#loop through the file list with lapply
dfs <-lapply(files, function(file) {
#read file
page <- read_xml(file)
#get id for each file
id <- xml_find_first(out, "//ip") %>% xml_attr("id_pac")
#get information from each the requested nodes
rodcis <- xml_find_first(out, ".//rodcis") %>% xml_text()
datod <- xml_find_first(out, ".//dat_od") %>% xml_text()
#make data frame of results for each file
data.frame(id, rodcis, datod)
})
#combine all results into 1 data frame
answer <- bind_rows(dfs)
我想阅读 XML 860 个文件。
所有 xml 个文件都具有
结构<ip id_pac="48">
<rodcis>48</rodcis>
<jmeno>Andrew</jmeno>
<prijmeni>Mazal</prijmeni>
<titul_pred></titul_pred>
<titul_za></titul_za>
<dat_dn format="D">1999-06-21</dat_dn>
<dat_de format="D"></dat_de>
<sex>M</sex>
<rod_prijm></rod_prijm>
<a typ="1">
<dat_od format="D">2020-09-17</dat_od>
</a>
</ip>
我想获取其中一列为“rodcis”(在本例中为 48)和第二列为“dat_od”(在本例中为 2020-09-17)的数据框
我正在尝试这个
- 获取所有 XML 个文件
files <- list.files(path = "~/Downloads/XML",
pattern = "*.xml",
full.names = TRUE)
- 获取包含所有 860 XML 个文件的列表(输出)
out <- lapply(files, xmlParse)
- 列表到数据框
dataframe <- do.call(rbind, lapply(out, function(x) rootnode[[1]][[2]], rootnode[[2]][[1]]))
但是出现了一个我不明白的错误。
cannot coerce type 'externalptr' to vector of type 'list'
这是使用 xml2 包的可能解决方案。有关分步指南,请参阅代码中的注释。
library(xml2)
library(dplyr)
#loop through the file list with lapply
dfs <-lapply(files, function(file) {
#read file
page <- read_xml(file)
#get id for each file
id <- xml_find_first(out, "//ip") %>% xml_attr("id_pac")
#get information from each the requested nodes
rodcis <- xml_find_first(out, ".//rodcis") %>% xml_text()
datod <- xml_find_first(out, ".//dat_od") %>% xml_text()
#make data frame of results for each file
data.frame(id, rodcis, datod)
})
#combine all results into 1 data frame
answer <- bind_rows(dfs)