使用XML获取HTML表

时间:2014-11-07 08:21:41

标签: html xml r

我正在尝试使用XML包读取一个html表,但即使它看起来很简单,我也没有设法做到这一点。我尝试了一切,但列的名称总是由R固定为V1,V2,V3,......

这是代码:

require(XML)

tbl <- readHTMLTable("http://facedata.ornl.gov/ornl/npp_98-08.html”,
header = c("year","ring","CO2", "stem","root","leaf","fine root", "NPP"), 
skip.rows=c(1,2),colClasses=c(rep("factor",3),rep("numeric",5)))

非常感谢你的帮助

1 个答案:

答案 0 :(得分:1)

表格的第一行造成了麻烦。删除它可能最简单:

library(XML)
appURL <- "http://facedata.ornl.gov/ornl/npp_98-08.html"
doc <- htmlParse(appURL)
removeNodes(doc["//table/tr[1]"]) # remove the first row with the troublesome header
myTable <- readHTMLTable(doc, which = 1)

> head(myTable)
  Year Plot  CO2 Stem Coarse Root Leaf Fine Root Total NPP
1 1998    1 elev 1540         127  362       168      2197
2 1998    2 elev 1487         139  418       175      2219
3 1998    3  amb 1085         112  333       231      1762
4 1998    4  amb 1204         113  368       185      1870
5 1998    5  amb 1136         109  382        56      1683
6 1999    1 elev 1218          98  475       295      2086