【问题标题】:How to convert xml data to data frame in R如何将xml数据转换为R中的数据框
【发布时间】:2015-01-05 10:15:56
【问题描述】:

大家好, 我需要将一个xml文件加载到R中的一个数据框中。xml格式如下图所示。我怎样才能达到同样的效果?

         <?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))

【问题讨论】:

  • 所需输出的结构究竟是什么?你有没有尝试过任何东西?我们不是来为您编写代码的。您应该展示您的尝试并描述它是如何失败的。我假设您尝试搜索问题至少让您可以使用 XML 包让 R 解析您的输入。
  • 您好,我尝试了以下代码库(XML) xml.url ="test.xml" xmlfile = xmlTreeParse(xml.url) class(xmlfile) xmltop=xmlRoot(xmlfile) print(xmltop) [1:2] plantcat
  • 我期待一个表格输出,其中我的列是“行 ID”、“PostTypeId”、“AcceptedAnswerId”、“CreationDate”、“Score”,然后是下面列出的 r 值(就像你在您查询数据库表)...

标签: xml r xml-parsing


【解决方案1】:
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(...)

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

【讨论】:

  • 您也可以使用 xmlAttrsToDataFrame。 XML:::xmlAttrsToDataFrame(xmlRoot(xml))
  • @ChrisS。 - 您应该将此作为答案发布。我不知道这个功能存在......我在文档的任何地方都找不到它。还有哪些其他无证掘金??
  • 我刚开始阅读新的 XML 和 Web 技术 for Data Sciences in R book 并在其中注意到它,但我不确定为什么没有更好地记录它。
猜你喜欢
  • 1970-01-01
  • 2021-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多