readHTMLTable | R Documentation |
This function and its methods provide somewhat robust methods for
extracting data from HTML tables in an HTML document.
One can read all the tables in a document given by filename or URL,
or having already parsed the document via htmlParse
.
Alternatively, one can specify an individual <table>
node in the document.
The methods attempt to do some heuristic computations to determine the header labels for the columns, the name of the table, etc.
readHTMLTable(doc, header = NA,
colClasses = NULL, skip.rows = integer(), trim = TRUE,
elFun = xmlValue, as.data.frame = TRUE, which = integer(),
...)
doc |
the HTML document which can be a file name or a URL
or an already parsed |
header |
either a logical value indicating whether the table has
column labels, e.g. the first row or a |
colClasses |
either a list or a vector that gives the names of
the data types for the different columns in the table, or
alternatively a function used to convert the string values to the
appropriate type. A value of In addition to the usual "integer", "numeric", "logical", "character", etc.
names of R data types, one can use
"FormattedInteger", "FormattedNumber" and "Percent" to specify that
format of the values are numbers possibly with commas (,) separating
groups of digits or a number followed by a percent sign (%).
This mechanism allows one to introduce new classes and specify these
as targets in |
skip.rows |
an integer vector indicating which rows to ignore. |
trim |
a logical value indicating whether to remove leading and trailing white space from the content cells. |
elFun |
a function which, if specified, is called when converting each cell. Currently, only the node is specified. In the future, we might additionally pass the index of the column so that the function has some context, e.g. whether the value is a row label or a regular value, or if the caller knows the type of columns. |
as.data.frame |
a logical value indicating whether to turn the resluting table(s) into data frames or leave them as matrices. |
which |
an integer vector identifying which tables to return from within the document. This applies to the method for the document, not individual tables. |
... |
currently additional parameters that are passed on to
|
If the document (either by name or parsed tree) is specified, the return value is a list of data frames or matrices. If a single HTML node is provided
Duncan Temple Lang
HTML4.0 specification
htmlParse
getNodeSet
xpathSApply
# u = "http://en.wikipedia.org/wiki/World_population"
u = "https://www.inflationdata.com/Inflation/Consumer_Price_Index/HistoricalCPI.aspx"
zz = readHTMLTable( paste(readLines(u), collapse = "\n" ))
# guard against the structure of the page changing.
if(any(i <- sapply(zz, function(x) if(is.null(x)) 0 else ncol(x)) == 14)){
zz = zz[[which(i)[1]]] # 4th table
# convert columns to numeric. Could use colClasses in the call to readHTMLTable()
zz[-1] = lapply(zz[-1], function(x) as.numeric(gsub(".* ", "", as.character(x))))
matplot(1:12, t(zz[-c(1, 14)]), type = "l")
}
## Not run:
# From Marsh Feldman on R-help
doc <- "http://www.nber.org/cycles/cyclesmain.html"
# The main table is the second one because it's embedded in the page table.
table <- getNodeSet(htmlParse(doc),"//table") [[2]]
xt <- readHTMLTable(table,
header = c("peak","trough","contraction",
"expansion","trough2trough","peak2peak"),
colClasses = c("character","character","character",
"character","character","character"),
trim = TRUE, stringsAsFactors = FALSE
)
## End(Not run)
if(FALSE) {
# Here is a totally different way of reading tables from HTML documents.
# The data are formatted using a PRE and so can be read via read.table
u = "http://tidesonline.nos.noaa.gov/data_read.shtml?station_info=9414290+San+Francisco,+CA"
h = htmlParse(u)
p = getNodeSet(h, "//pre")
con = textConnection(xmlValue(p[[2]]))
tides = read.table(con)
}
u = "https://en.wikipedia.org/wiki/List_of_countries_by_population"
doc = htmlParse( readLines(u) )
tables = readHTMLTable(doc)
names(tables)
tables[[1]]
# Print the table. Note that the values are all characters
# not numbers. Also the column names have a preceding X since
# R doesn't allow the variable names to start with digits.
tmp = tables[[2]]
# Let's just read the second table directly by itself.
tableNodes = getNodeSet(doc, "//table")
tb = readHTMLTable(tableNodes[[1]])
# Let's try to adapt the values on the fly.
# We'll create a function that turns a th/td node into a val
tryAsInteger = function(node) {
val = xmlValue(node)
ans = as.integer(gsub(",", "", val))
if(is.na(ans))
val
else
ans
}
tb = readHTMLTable(tableNodes[[2]], elFun = tryAsInteger)
tb = readHTMLTable(tableNodes[[2]], elFun = tryAsInteger,
colClasses = c("character", rep("integer", 9)))
## Not run:
if(require(RCurl) && url.exists("http://www.omegahat.net/RCurl/testPassword/table.html")) {
tt = getURL("http://www.omegahat.net/RCurl/testPassword/table.html", userpwd = "bob:duncantl")
readHTMLTable(tt)
}
## End(Not run)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.