title: R scrape HTML table with multiple subheaders
body: <p>I'm trying to import the list of nuclear test sites (from Wikipedia's page) in a data.frame using the code below:</p>
  
  <pre><code>library(RCurl)
  library(XML)
  
  theurl &lt;- "https://en.wikipedia.org/wiki/List_of_nuclear_test_sites"
  webpage &lt;- getURL(theurl)
  webpage &lt;- readLines(tc &lt;- textConnection(webpage)); close(tc)
  
  pagetree &lt;- htmlTreeParse(webpage, error=function(...){}, useInternalNodes = TRUE)
  
  # Find XPath (go the webpage, right-click inspect element, find table then right-click copyXPath) 
  myxpath &lt;- "//*[@id='mw-content-text']/table[2]"
  
  # Extract table header and contents
  tablehead &lt;- xpathSApply(pagetree, paste(myxpath,"/tr/th",sep=""), xmlValue)
  results &lt;- xpathSApply(pagetree, paste(myxpath,"/tr/td",sep=""), xmlValue)
  
  # Convert character vector to dataframe
  content &lt;- as.data.frame(matrix(results, ncol = 5, byrow = TRUE))
  names(content) &lt;- c("Testing country", "Location", "Site", "Coordinates", "Notes")
  </code></pre>
  
  <p>However there are multiple sub-headers that prevent the data.frame to be populated consistently. How can I fix this?</p>