[R] (simple) xml into data.frame and reverse
stefan.duke at gmail.com
stefan.duke at gmail.com
Tue Jul 14 23:40:10 CEST 2009
Hello,
I am trying to convert a simple data.frame (it will always be a few
equally long variables) into the XML format (which I don't understand
too well but need as input for another program) and reverse the
operation (from XML back into data.frame).
I found some code which does the first and it works good enough for me
(see below). Is there an easy way to reverse the operation? My XML
files are nothing fancy (no child nodes or anything, at least as far
as I can see.
### data.frame
data<- as.data.frame(cbind(c( 0 , 1 ),c( 500 , 300),c(200, 400)))
names(data)<-c("age","0","1")
### converts data.frame into XML
xml <- xmlTree()
xml$addTag("populationsize", close=FALSE)
for (i in 1:nrow(data)) {
xml$addTag("size", close=FALSE)
for (j in names(data)) {
xml$addTag(j, data[i, j])
}
xml$closeTag()
}
xml$closeTag()
# view the result
cat(saveXML(xml))
I put below also an example of how my data looks like.
Thanks for any advice!
Best and have a great day,
Stefan
APPENDIX
XML-file
------------------
<populationsize>
<size>
<age>0</age>
<sex>0</sex>
<number>500</number>
</size>
<size>
<age>0</age>
<sex>1</sex>
<number>300</number>
</size>
<size>
<age>1</age>
<sex>0</sex>
<number>200</number>
</size>
<size>
<age>1</age>
<sex>1</sex>
<number>400</number>
</size>
</populationsize>
---------
DATAFRAME
age 0 1
0 500 300
1 200 400
More information about the R-help
mailing list