我有一个像这样的 html 和 R 代码,需要将每个节点值与 data.frame 中的父 ID 相关联。每个人都有一些不同的信息。
example <- "<div class='person' id='1'>
<div class='phone'>555-5555</div>
<div class='email'>jhon@123.com</div>
</div>
<div class='person' id='2'>
<div class='phone'>123-4567</div>
<div class='email'>maria@gmail.com</div>
</div>
<div class='person' id='3'>
<div class='phone'>987-6543</div>
<div class='age'>32</div>
<div class='city'>New York</div>
</div>"
doc = htmlTreeParse(example, useInternalNodes = T)
values <- xpathSApply(doc, "//*[@class='person']/div", xmlValue)
variables <- xpathSApply(doc, "//*[@class='person']/div", xmlGetAttr, 'class')
id <- xpathSApply(doc, "//*[@class='person']", xmlGetAttr, 'id')
# The problem: create a data.frame(id,variables,values)
使用xpathSApply()
,我也可以获得电话、电子邮件和年龄值以及人员属性 (id)。但是,这些信息是孤立的,我需要将它们引用到正确的 data.frame 变量和正确的人。在我的真实数据中有很多不同的信息,所以这个命名每个变量的过程必须是自动的。
我的目标是创建一个像这样的 data.frame,将每个 id 与其适当的数据相关联。
id variables values
1 1 phone 555-5555
2 1 email jhon@123.com
3 2 phone 123-4567
4 2 email maria@gmail.com
5 3 phone 987-6543
6 3 age 32
7 3 city New York
我相信我必须创建一个在内部使用的函数,该函数xpathSApply
将同时获得人员电话和人员 ID,因此它们是相关的,但到目前为止我还没有取得任何成功。
谁能帮我?