How to convert xml data to data frame in R

荒凉一梦 提交于 2019-12-08 04:11:15
xml.text <- 
'<?xml version="1.0" encoding="utf-8"?>
<posts>  
<row Id="1" PostTypeId="1" AcceptedAnswerId="17" CreationDate="2010-07-26T19:14:18.907" Score="6"/>
<row Id="2" PostTypeId="1" AcceptedAnswerId="17" CreationDate="2010-07-26T19:14:18.907" Score="6"/>
<row Id="3" PostTypeId="1" AcceptedAnswerId="17" CreationDate="2010-07-26T19:14:18.907" Score="6"/>
<row Id="4" PostTypeId="1" AcceptedAnswerId="17" CreationDate="2010-07-26T19:14:18.907" Score="6"/>
</posts>'

library(XML)
xml <- xmlParse(xml.text)
result <- as.data.frame(t(xmlSApply(xml["/posts/row"],xmlAttrs)),
                        stringsAsFactors=FALSE)
#   Id PostTypeId AcceptedAnswerId            CreationDate Score
# 1  1          1               17 2010-07-26T19:14:18.907     6
# 2  2          1               17 2010-07-26T19:14:18.907     6
# 3  3          1               17 2010-07-26T19:14:18.907     6
# 4  4          1               17 2010-07-26T19:14:18.907     6

This is a bit trickier than usual because the data is in attributes, not nodes (the nodes are empty), so we can't use xlmToDataFrame(...) unfortunately.

All the data above is still character, so you still need to convert the columns to whatever class is appropriate.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!