如何为数据框中的每一行获取单独的 XML 格式? [英] How to get a separated XML format for each row in a data frame?

查看:20
本文介绍了如何为数据框中的每一行获取单独的 XML 格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的数据框导出为 XML 格式.在数据框-结果"中,我有两列两行.
我使用此代码:

I want to export my data frame to XML format. In the data frame- "results" I have two columns and two rows.
I use this code:

xmlNode("data",.children=lapply(names(results),function(n){xmlNode(n,results[[n]])}))   

结果喜忧参半:

<data> <time>2013-10-27 13:00:002013-10-27 13:00:00</time>
<p_value>0.990.79</p_value> </data>`

输入到同一个 XML 节点的两行.我将有超过 2 行,所以我希望能够为每一行获取单独的 XML 格式,如下所示:

The two rows entered to the same XML node. I will have more than 2 rows so I want to be able to get separated XML format for each row, like that:

<data> 
<time>2013-10-27 13:00:00</time>
<p_value>0.99</p_value>
</data>

下一行将如下所示:

<data> 
<time>2013-10-27 13:00:00</time>
<p_value>0.79</p_value>
</data

我的问题是如何分隔 XML 格式的行?

My question is how to separate the rows in XML format?

推荐答案

让我们从一些虚拟数据开始:

Let's start with some dummy data:

dt <- data.frame( x = 1:10, y = LETTERS[1:10] )

在您的示例中,您正在应用 data.frame 列(使用 lapply),尽管您解释说,您更愿意应用在行上.然后它看起来像这样:

In your example you are applying over the data.frame columns (using lapply) although you explain, that you'd rather want to apply over rows. Then it would look like this:

xmlNode( "data", .children = apply(
  dt, 1, function(n){
    xmlNode( "row", 
      xmlNode( names(dt)[1], n[1] ),
      xmlNode( names(dt)[2], n[2] )
    )
  }
))   

<data>
 <row>
  <x> 1</x>
  <y>A</y>
 </row>
 <row>
  <x> 2</x>
  <y>B</y>
...

通用解决方案

如果您正在寻找更通用的解决方案,将任意 data.frame 转换为 xml 节点,您可以使用以下解决方案:

Generic solution

And if you are looking for a more general solution, to convert an arbitrary data.frame to an xml node, you could use this solution:

library(plyr)
xmlNode( "data", .children =
  alply( results, 1, function(row)
    xmlNode( "row", 1, .children = alply( row , 2, function(cell) xmlNode( names(cell), cell ) ) )
  )
)

这篇关于如何为数据框中的每一行获取单独的 XML 格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆