Last active
          May 28, 2016 21:51 
        
      - 
      
- 
        Save data-steve/7532614be98c26e65107c73a5ad0c76a to your computer and use it in GitHub Desktop. 
    in response to @daattali's request to extract html tables with links included: https://twitter.com/daattali/status/717582654476914688
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | #compare with https://gist.github.com/expersso/bb03efcab2a6c125da5ac22e1c33d070 | |
| url <- "https://github.com/daattali/addinslist/blob/master/README.md#list-of-addins" | |
| get_html_table <- function(url){ | |
| xx <- xml2::read_html(url) | |
| rvest::xml_node(rvest::xml_node(xx,"body"),"table") | |
| } | |
| tr_to_nms <- function(tbl){ | |
| tbl_tr <- rvest::xml_nodes(rvest::xml_nodes(tbl,"thead"),'tr') | |
| tbl_tr <- sapply(tbl_tr, function(x) gsub("(<th/>)", "<th>''</th>", x)) | |
| sapply(tbl_tr, function(x) { | |
| strsplit(gsub("(<tr>\n<th>)|(</th>\n</tr>)","",x),"(</th>\n<th>)")[[1]] | |
| } , USE.NAMES=FALSE) | |
| } | |
| tr_to_df <- function(tbl){ | |
| tbl_df <- rvest::xml_nodes(rvest::xml_nodes(tbl,"tbody"),'tr') | |
| tbl_df <-sapply(tbl_df, function(x) gsub("(<td/>)", "<td>''</td>", x)) | |
| as.data.frame( | |
| t(sapply(tbl_df, function(x) { | |
| strsplit(gsub("(<tr>\n<td>)|(</td>\n</tr>)","",x),"(</td>\n<td>)")[[1]] | |
| }, USE.NAMES = F)) | |
| ,stringsAsFactors=FALSE) | |
| } | |
| get_table <- function(url){ | |
| xml_table <- get_html_table(url) | |
| stats::setNames(tr_to_df(xml_table),tr_to_nms(xml_table)) | |
| } | |
| df <- get_table(url) | |
| dplyr::glimpse(df) | |
| # Observations: 28 | |
| # Variables: 7 | |
| # $ Name (chr) "Browse RStudio addins", "Colour picker", "ggplot2 Marginal Plots", "ggplot Theme Assist", "S... | |
| # $ Description (chr) "Browse and install RStudio addins", "Lets you easily select colours", "Add marginal plots to... | |
| # $ Package (chr) "<a href=\"https://github.com/daattali/addinslist\">addinslist</a>", "<a href=\"https://githu... | |
| # $ On CRAN? (chr) "<g-emoji alias=\"white_check_mark\" fallback-src=\"https://assets-cdn.github.com/images/icon... | |
| # $ Author (chr) "<a href=\"http://deanattali.com/\">Dean Attali</a>", "<a href=\"http://deanattali.com/\">Dea... | |
| # $ More links (chr) "<a href=\"https://raw.githubusercontent.com/daattali/addinslist/master/inst/media/addin.png\... | |
| # $ Notes (chr) "''", "''", "''", "''", "''", "''", "''", "''", "''", "Doesn't work on Windows", "''", "''", ... | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment