这是我第一次使用XML使用R,所以我的问题可能听起来很天真,如果不是愚蠢的话……我下载了一个XML文件,格式是
<experiment>
<sampleattribute>
<category>AGE</category>
<value>8</value>
<value>10</value>
<value>11</value>
</sampleattribute>
<sampleattribute>
<category>SEX</category>
<value>female</value>
<value>male</value>
</sampleattribute>
</experiment>
<experiment>
<sampleattribute>
<category>DESIGN</category>
<value>control</value>
<value>disease</value>
</sampleattribute>
</experiment>
<experiment>
<sampleattribute>
<category>AGE</category>
<value>8</value>
<value>10</value>
<value>11</value>
</sampleattribute>
<sampleattribute>
<category>SEX</category>
<value>female</value>
</sampleattribute>
<sampleattribute>
<category>DESIGN</category>
<value>control</value>
<value>disease</value>
</sampleattribute>
</experiment>如您所见,每个实验节点都有不同的sampleattribute。我希望将每个实验中的所有sampleattribute连接在一起,最终将其转换为数据帧。
我已经尝试了attr<- xpathSApply(myxml,“//实验/sampleattribute”),但是没有办法追踪哪个实验有什么sampleattirbutes。
非常感谢您的任何建议。
发布于 2014-04-08 21:12:41
您不能用这样的XML得到一个dataframe,而只能得到一个列表。
使用XML包,您可以执行此操作,例如:
doc = htmlParse(txt,asText=TRUE)
res = lapply(xpathSApply(doc,'//experiment'),
function(x){
category = xpathSApply(x,'sampleattribute/category',xmlValue)
values = xpathSApply(x,'sampleattribute/value',xmlValue)
list(category=category,
values =values)
})然后你可以检查你的结果:
str(res)
List of 3
$ :List of 2
..$ category: chr [1:2] "AGE" "SEX"
..$ values : chr [1:5] "8" "10" "11" "female" ...
$ :List of 2
..$ category: chr "DESIGN"
..$ values : chr [1:2] "control" "disease"
$ :List of 2
..$ category: chr [1:3] "AGE" "SEX" "DESIGN"
..$ values : chr [1:6] "8" "10" "11" "female" ..https://stackoverflow.com/questions/22937424
复制相似问题