I am trying to use the following syntax to get the occupation information from George Clooney's wikipedia page. Eventually I would like there to be a loop to get data on various personalitys' occupations.
However, I get the following problem running the below code:
Error in if (symbol != "role") symbol = NULL : argument is of length zero
I am not sure why this keeps on coming up.
library(XML)
library(plyr)
url = 'http://en.wikipedia.org/wiki/George_Clooney'
# don't forget to parse the HTML, doh!
doc = htmlParse(url)
# get every link in a table cell:
links = getNodeSet(doc, '//table/tr/td')
# make a data.frame for each node with non-blank text, link, and 'title' attribute:
df = ldply(links, function(x) {
text = xmlValue(x)
if (text=='') text=NULL
symbol = xmlGetAttr(x, 'class')
if (symbol!='role') symbol=NULL
if(!is.null(text) & !is.null(symbol))
data.frame(symbol, text) } )
As @gsee mentioned, you need to check that symbol
isn't NULL
before you check its value. Here's a minor update to your code that works (at least for George).
df = ldply(
links,
function(x)
{
text = xmlValue(x)
if (!nzchar(text)) text = NULL
symbol = xmlGetAttr(x, 'class')
if (!is.null(symbol) && symbol != 'role') symbol = NULL
if(!is.null(text) & !is.null(symbol))
data.frame(symbol, text)
}
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With