2014-11-08 142 views
1

大家好, 我需要将一个xml文件加载到R中的数据框中。xml格式如下所示。我如何获得同样的成绩?如何将xml数据转换为R中的数据帧

  <?xml version="1.0" encoding="utf-8"?><posts> <row Id="1" PostTypeId="1" AcceptedAnswerId="17" CreationDate="2010-07-26T19:14:18.907" Score="6"/></posts> 

我试过下面的代码....它没有给出所需的输出。我期待一个列表输出,列名和它们的值列在下面。

library(XML) 
xml.url ="test.xml" 
xmlfile = xmlTreeParse(xml.url) 

class(xmlfile) 
xmltop=xmlRoot(xmlfile) 

print(xmltop)[1:2] 

plantcat <- xmlSApply(xmltop, function(x) xmlSApply(x, xmlValue)) 

plantcat_df <- data.frame(t(plantcat)) 
+1

所需输出的结构究竟是什么?你有没有尝试过任何东西?我们不是在这里为你写代码。你应该展示你的尝试并描述它是如何失败的。我假设你尝试谷歌这个问题,至少让你到R的'XML'包解析你的输入。 – MrFlick 2014-11-08 20:35:16

+0

您好,我试图下面的代码库(XML) xml.url = “的test.xml” XMLFILE = xmlTreeParse(xml.url) 类(XMLFILE) xmltop = xmlRoot(XMLFILE) 打印(xmltop) [1:2] plantcat < - xmlSApply(xmltop,函数(X)xmlSApply(X,xmlValue)) plantcat_df < - data.frame(吨(plantcat)) – Zack 2014-11-08 20:48:29

+0

我期待一个表格输出,其中i有列作为“行ID”,“PostTypeId”,“AcceptedAnswerId”,“CreationDate”,“分数”,然后r值列在下面(就像你在查询数据库表时一样)... – Zack 2014-11-08 20:51:51

回答

3
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 

这比平时麻烦一些,因为数据是属性,而不是节点(节点是空的),所以我们不能用xlmToDataFrame(...)不幸。

上面的所有数据仍然是字符,所以您仍然需要将列转换为适合的类。

+0

你也可以使用xmlAttrsToDataFrame。 XML ::: xmlAttrsToDataFrame(xmlRoot(xml)) – 2014-11-17 16:05:05

+0

@ChrisS。 - 你应该发布这个答案。我不知道这个函数是否存在......我在文档的任何地方都找不到它。还有什么其他无证矿块? – jlhoward 2014-11-17 16:25:53

+0

我刚刚开始阅读Data Sciences in R book中的新XML和Web技术,并在那里注意到它,但我不确定它为什么没有更好的文档记录。 – 2014-11-17 20:54:33