I am trying to transform an XML file into a dataframe.
Example xml file:
<games id="32134">
<game id="3962920" xsid="0">
<time>2016-11-26T15:30:00+00:00</time>
<group id="33765">Roses</group>
<hteam id="2228">BlackSavers</hteam>
<ateam id="226150">Regeton</ateam>
<results>
</results>
<server sid="126" name="reg">
<offer id="548331136">
<states i="0" time="2016-11-26T10:03:56+00:00" starting_time="2016-11-26T15:30:00+00:00">
<s1>2.750</s1>
<s2>3.600</s2>
<s3>2.100</s3>
</states>
<states i="1" time="2016-11-25T17:05:07+00:00" starting_time="2016-11-26T15:30:00+00:00">
<s1>3.000</s1>
<s2>3.600</s2>
<s3>2.000</s3>
</states>
</offer>
</server>
<server bid="221" name="razor">
<offer id="548415893">
<states i="0" time="2016-11-26T10:11:26+00:00" starting_time="2016-11-26T15:30:00+00:00">
<s1>653.000</s1>
<s2>873.600</s2>
<s3>225.100</s3>
</states>
<states i="1" time="2016-11-26T10:07:39+00:00" starting_time="2016-11-26T15:30:00+00:00">
<s1>323.000</s1>
<s2>321.750</s2>
<s3>211.050</s3>
</states>
<states i="2" time="2016-11-25T19:54:20+00:00" starting_time="2016-11-26T15:30:00+00:00">
<s1>223.100</s1>
<s2>322.600</s2>
<s3>232.050</s3>
</states>
</offer>
</server>
<server bid="291" name="nagie">
<offer id="548454059">
<states i="0" time="2016-11-26T13:21:08+00:00" starting_time="2016-11-26T15:30:00+00:00">
<s1>323.000</s1>
<s2>123.400</s2>
<s3>342.100</s3>
</states>
<states i="1" time="2016-11-26T10:07:02+00:00" starting_time="2016-11-26T15:30:00+00:00">
<s1>123.000</s1>
<s2>323.500</s2>
<s3>342.050</s3>
</states>
<states i="2" time="2016-11-25T21:35:50+00:00" starting_time="2016-11-26T15:30:00+00:00">
<s1>374.000</s1>
<s2>349.600</s2>
<s3>200.000</s3>
</states>
</offer>
</server>
</game>
</games>
Current code:
df <- do.call("rbind", xpathApply(doc, "//game", function(m) {
data.frame(
game_id = xmlAttrs(m)["id"],
t(xpathSApply(m, "group", function(g) {
c(
group_id = xmlAttrs(g)["id"],
group = xmlValue(g[["group"]])
)
})),
t(xpathSApply(m, "server",function(b){
sid <- xmlAttrs(b)[["sid"]]
name <- xmlAttrs(b)[["name"]]
xpathSApply(b, "offer",function(of){
c(
sid = sid,
name = name,
id = xmlAttrs(of)[["id"]],
do.call(cbind, xpathApply(of, "states",function(o){
c(s1 <- xmlValue(o[["s1"]]),
s2 <- xmlValue(o[["s2"]]),
s3 <- xmlValue(o[["s3"]])
)
}))
)})
})))
}))
Desired dataframe output:
My problem is, I can't figure out how to place states in the dataframe as well. The other levels are already in, and they do work. I would only need help for the last piece.
These posts helped me a lot xml with nested siblings to data frame in R Transforming data from xml into R dataframe
Thank you!