《List of World Heritage in Danger》
导包
  1. library(stringr)
  2. library(XML)
  3. library(maps)
  4. heritage_parsed <- htmlParse("http://en.wikipedia.org/wiki/List_of_World_Heritage_in_Danger",encoding = "UTF-8")

出现错误

  1. Error: failed to load external entity "

网上查阅了相关的资料:
并不能有效的解决,so,只好去翻阅errata

page 2

Credit: Suryapratim Sarkar (2015-06-25)

Wikipedia changed its server communication from HTTP to HTTPS. As a result, the following lines on page 2 return an error:(的确,如果你直接粘贴原http协议的地址,浏览器的地址栏会自动帮你转成https)

heritage_parsed <- htmlParse("http://en.wikipedia.org/wiki/List_of_World_Heritage_in_Danger",
encoding = "UTF-8")
## Error: failed to load external entity "http://en.wikipedia.org/wiki/List_of_World_Heritage_in_Danger"

There are at least two solutions to the problem:

  1. Use getURL() and specify the location of CA signatures (see Section 9.1.7 of our book).

  2. Use Hadley Wickham’s rvest package, which came out after our book was published. It facilitates scraping with R considerably, in particular in such scenarios(情形、脚本). In this specific example, use the following code instead:

library(rvest) # the new package, version 0.3.0
heritage_parsed <- read_html("http://en.wikipedia.org/wiki/List_of_World_Heritage_in_Danger", encoding = "UTF-8") # read_html() from the rvest package is the new htmlParse() from the XML package
tables <- html_table(heritage_parsed, fill = TRUE) # html_table() from the rvest package, which replaces readHTMLTable() from the XML package

From thereon, the rest of the chapter code should work. If you want to learn more about the rvest package, have a look here. We are planning to cover it extensively in the next edition of our book.


另外注意,网址太长,太也不要随便的回车换行,否则各种错。另外html_table会出现关闭不用的网址链接的警告,无碍事的。

我们进入网址:
其中我们真正感兴趣的是如下这个表
 
read_html函数返回的应该是经过pars的,但具体的细节我还没那么清晰
  1. heritage_parsed <- read_html(
  2.   "http://en.wikipedia.org/wiki/List_of_World_Heritage_in_Danger", encoding = "UTF-8")
  3. # str(heritage_parsed)
  4. #我曾经尝试将heritage_parsed写到本地文件,但是失败了
  5. #无法将list通过cat()输入到本地,查阅了sof,但是还是没有解决

  1. #从heritage_parsed中取出所有的表格
  2. tables <- html_table(heritage_parsed, fill = TRUE) 
  3. #所以,我怎么知道这是第二个表格呢?
  4. danger_table <- tables[[2]]
  5. #查看表格的列名
  6. names(danger_table)
  7. # [1] "Name"            "Image"           "Location"       
  8. # [4] "Criteria"        "Area\nha (acre)" "Year (WHS)"     
  9. # [7] "Endangered"      "Reason"          "Refs"

取出表格中的1, 3, 4, 6, 7列,其含义分别是名字、位置、标准分类、申遗成功时间、何时定为处于危险的时间

  1. #感兴趣的只有表格中的1, 3, 4, 6, 7列
  2. #名字、位置、标准分类、申遗成功时间、何时定为处于危险的时间
  3. #覆盖掉原来的表格
  4. danger_table <- danger_table[, c(1, 3, 4, 6, 7)]
  5. #为了更方便,对列重命名,
  6. colnames(danger_table) <- c("name", "locn", "crit", "yins", "yend")
  7. #取几个遗产的名字查看下
  8. danger_table$name[1:3]

数据的初步整理和清洗
  1. #str_detect是stringr包中的函数
  2. #用于在前一个参数中按照后一个参数的规则查找是否存在特定字符
  3. #返回值是逻辑值向量
  4. #对crit列按照自然和人文遗产重新编码
  5. #Natural景观遗产编码为nat,否则为culture,即cul
  6. danger_table$crit <- ifelse(
  7.   str_detect(danger_table$crit, "Natural") ==TRUE, 
  8.   "nat", 
  9.   "cult"
  10.   )
注意,其中str_detect是stringr包中的函数,看一个例子(反正大家帮助文档随查随用么)
  1. fruit <- c("apple", "banana", "pear", "pinapple")
  2. str_detect(fruit, "a")
  3. # [1] TRUE TRUE TRUE TRUE

我们可以看到yins的时间是xxxx-的格式,大部分是2001-,有些甚至是1993–2007, 2010-
我们只取第一次的吧
  1. # 将申遗成功时间转为数值类型
  2. danger_table$yins <- as.numeric(danger_table$yins)
  3. #按照正则表达式取出(我们只取出濒危时间,去掉横杠,并转化为数值型)
  4. yend_clean <- unlist(
  5.   str_extract_all(danger_table$yend, "[[:digit:]]4$")
  6.   )
实际上,上述正则表达式并不OK,得到的是空字符串,所以,我只好自己修改了
  1. yend_clean1 <- unlist(str_extract_all(danger_table$yend, "\\d{4}-"))
  2. yend_clean <- unlist(str_extract_all(yend_clean1, "\\d{4}"))
  3. length(yend_clean)
  4. length(danger_table$yend)
  5. danger_table$yend <- as.numeric(yend_clean)
  6. danger_table$yend[1:3]
  7. #[1] 2001 1992 2013

str_extract_all也是stringr包中的函数,看个例子,自己体会~
str_extract_all函数的返回值是一个list,所以要unlist
  1. shopping_list <- c("apples x4", "bag of flour", "bag of sugar", "milk x2")
  2. str_extract(shopping_list, "\\d")
  3. # [1] "4" NA  NA  "2"
  4. str_extract(shopping_list, "[a-z]+")
  5. # [1] "apples" "bag"    "bag"    "milk"  
  6. str_extract_all(shopping_list, "[a-z]+")
  7. # [[1]]
  8. # [1] "apples" "x"     
  9. # [[2]]
  10. # [1] "bag"   "of"    "flour"
  11. # [[3]]
  12. # [1] "bag"   "of"    "sugar"
  13. # [[4]]
  14. # [1] "milk" "x"   

位置列中的信息相对比较杂乱,我们还是要整理
  1. danger_table$locn[c(1, 3, 5)]
  2. [1] "EgyAbusir, Egypt30°50′30″N 29°39′50″E / 30.84167°N 29.66389°E / 30.84167; 29.66389 (Abu Mena)"                                   
  3. [2] "Syria !Aleppo Governorate,  Syria36°14′0″N 37°10′0″E / 36.23333°N 37.16667°E / 36.23333; 37.16667 (Ancient City of Aleppo)"      
  4. [3] "Syria !Damascus Governorate,  Syria33°30′41″N 36°18′23″E / 33.51139°N 36.30639°E / 33.51139; 36.30639 (Ancient City of Damascus)"
仔细观察,表格,其实已经给出了经纬度,这是我们需要的参数,点击还能显示地图哦~

再认真看一下1、2、3行的数据

 我们可以发现30°50′30″N 29°39′50″E / 30.84167°N 29.66389°E / 30.84167; 29.66389不过是三种不同的经纬度书写格式而已。
这里我们对最后一种展示格式找出其一般规律使用正则表达式
#正则表达式
  1. reg_y <- "[/][ -]*[[:digit:]]*[.]*[[:digit:]]*[;]"
  2. reg_x <- "[;][ -]*[[:digit:]]*[.]*[[:digit:]]*"
其实[[:digit:]]应该等价于\\d吧?
[/][ -]*\\d*[.]*\\d*[;]

第一段:以反斜杠/开头,或者以空格和横杠-开头,

第二段:任意多个的数字
第三段:一个点分割
第四段:以分号结尾

下面再去掉无关的字符
  1. y_coords <- str_extract(danger_table$locn, reg_y)
  2. y_coords
  3.  [1] "/ 30.84167;"    "/ 18.283;"      "/ 36.23333;"   
  4.  [4] "/ 32.51806;"    "/ 33.51139;"    "/ 36.33417;"   
  5.  [7] "/ 32.82500;"    "/ 32.63833;"    "/ 32.80528;"   
  6. [10] "/ 35.45667;"    "/ 42.26222;"    "/ 17.317;"     
  7. [13] "/ -8.11111;"    "/ 31.70444;"    "/ 9.167;"      
  8. [16] "/ 11.417;"      "/ 34.78167;"    "/ 34.83194;"   
  9. [19] "/ -11.68306;"   "/ 25.317;"      "/ 9.55389;"    
  10. [22] "/ 4.000;"       "/ 35.58806000;" "/ 39.05000;"   
  11. [25] "/ 14.200;"      "/ -20.20833;"   "/ -2.500;"     
  12. [28] "/ 53.40667;"    "/ 9.000;"       "/ 34.39667;"   
  13. [31] "/ 42.66111;"    "/ 7.600;"       "/ 6.83972;"    
  14. [34] "/ 13.000;"      "/ 2.000;"       "/ 31.77667;"   
  15. [37] "/ 15.35556;"    "/ 30.13333;"    "/ 13.90639;"   
  16. [40] "/ 15.92694000;" "/ -14.467;"     "/ 15.74444;"   
  17. [43] "/ 24.83333;"    "/ -8.95778;"    "/ -2.000;"     
  18. [46] "/ 34.200;"      "/ 13.183;"      "/ 34.55417;"   
  19. [49] "/ 16.77333;"    "/ 16.2893333;"  "/ 0.32917;"    
  20. [52] "/ -2.500;"      "/ 0.917;"       "/ 31.71972;"   
怪了,为什么会出现-呢?经纬度还有负的?如果是分隔符也不该采用啊
查阅之后得到:

负纬度表示位于南半球(S)的位置而负经度表示西半球(W)的位置.

所以我们上面的正则不是横杠,是负号
#截取和加入到表中
  1. y_coords <- as.numeric(str_sub(y_coords, 3, -2))
  2. danger_table$y_coords <- y_coords
其中str_sub(y_coords, 3, -2)的意思是,从第三个字符开始截取,到倒数第二个结束(保留必要的精度吧2)
另一个同理
  1. x_coords <- str_extract(danger_table$locn, reg_x)
  2. x_coords <- as.numeric(str_sub(x_coords, 3, -1))
  3. danger_table$x_coords <- x_coords
  4. danger_table$locn <- NULL
  5. names(danger_table)
  6. # [1] "name" "crit" "yins" "yend" "y_coords"
  7. # [6] "x_coords"
  8. round(danger_table$y_coords, 2)[1:3]
  9. round(danger_table$x_coords, 2)[1:3]
其中danger_table$locn <- NULL是删除danger_table中的locn列

round(danger_table$y_coords, 2)的作用是取小数点后两位,这里只是起到了查看的作用,并没有影响表中的数据


  1. #查看维度
  2. dim(danger_table)
  3. head(danger_table)
(维度和课本不一致很正常,可能是维基百科又更新了一些濒危的名单)

下面就对其进行制图啦,看看这些不同的遗产
  1. #对人文和自然景观设置不同的点的形状
  2. pch <- ifelse(danger_table$crit == "nat", 10, 11)
  3. #对分属人文和自然景观的遗产设置不同的颜色参数
  4. cols <- ifelse(danger_table$crit == "nat", 'deepskyblue4', 'brown1')
  5. #嗯,输入到本地文件,免得RStudio的绘图窗口太小
  6. #注意宽高的调整
  7. png("d:\\map.png",width = 1300, height = 720)  
  8. map("world", col = "maroon", 
  9.     lwd = 0.5, 
  10.     mar = c(0.1, 0.1, 0.1, 0.1),
  11.     bg='seashell')
  12. points(danger_table$x_coords, 
  13.        danger_table$y_coords, 
  14.        pch = pch,
  15.        col=cols,
  16.        cex=1.2,lwd=1.3
  17.        )
  18. #添加图例
  19. #leg.txt中设置的是图例文本
  20. leg.txt <- c("Natural", "Cultural")
  21. #当取x=0,y=0的时候是位于图正中央
  22. #text.col设置图例文字颜色
  23. #cex设置图例区域大小
  24. legend("topright", leg.txt, horiz = TRUE, 
  25.        pch=c(10, 11),
  26.        col = c('deepskyblue4', 'brown1'),
  27.        text.col=c('deepskyblue4', 'brown1'),
  28.        cex =2.3)
  29. #box是边框,其样式lty的参数有点意思哈
  30. box(lty='1373', lwd =5,col = 'red')
  31. #关闭输出设备
  32. dev.off()  
图如下:
 啊,果然还是非洲穷啊,没有经费保护?所以说呢,不要有大量的资金可以申遗,却没有资金去维护啊。


频数表
  1. table(danger_table$crit)
  2. #
  3. # cult  nat 
  4. # 37   17 
为什么人文的遗产濒危的更多一些?也许是传承出现了问题吧.....自然的变化,相对是缓慢的UI吧?

  1. library(RColorBrewer)
  2. cols1=brewer.pal(8,'Set3')
  3. par(bg='lightcyan')
  4. hist(danger_table$yend,
  5.      freq = TRUE,
  6.      xlab = "Year when site was put on the list of endangered sites",
  7.      col=cols1,border = cols1,
  8.      main = "")
 为什么2000年后反而多起来了?有意思,其实可以看看自然和人文景观各自的濒危情况随着时间的变化的

#奇怪的样式

  1. cols2=brewer.pal(8,'Paired')
  2. par(bg='lightcyan')
  3. hist(
  4.      danger_table$yend,
  5.      freq = TRUE,density = TRUE,
  6.      xlab = "Year when site was put on the list of endangered sites",
  7.      col=cols2,main = "")
 好了好了,我们只是做个试验示例对不对?具体的挖掘,留待以后吧。

唉呀,我岂不是可以用来抓取淘宝的商品评论,进行评价分析?


R自动数据收集第一章概述——《List of World Heritage in Danger》的更多相关文章

  1. R自动数据收集第二章HTML笔记1(主要关于handler处理器函数和帮助文档所有示例)

    本文知识点:     1潜在畸形页面使用htmlTreeParse函数 2startElement的用法 3闭包 4handler函数的命令和函数体主要写法 5节点的丢弃,取出,取出标签名称.属性.属 ...

  2. R自动数据收集第二章HTML笔记2(主要关于htmlTreeParse函数)

    包含以下几个小的知识点 1htmlTreeParse函数源码和一些参数 2hander的写法 3关于missing函数 4关于if-else语句中else语句的花括号问题 5关于checkHandle ...

  3. 【译文连载】 理解Istio服务网格(第一章 概述)

    书籍英文版下载链接为 https://developers.redhat.com/books/introducing-istio-service-mesh-microservices/,作者 Burr ...

  4. TCP/IP详解 卷1 第一章概述

    第一章概述 1.2 分层 网络编程通常分不同层次进行开发,每一层负责不同的通信功能. 一个协议族比如TCP/IP,通常是一组不同层次上多个协议的组合.一般可以认为是是四层协议系统: 链路层:有时也称作 ...

  5. perl5 第一章 概述

    第一章 概述 by flamephoenix 一.Perl是什么?二.Perl在哪里?三.运行四.注释 一.Perl是什么?      Perl是Practical Extraction and Re ...

  6. 计算机网络课程优秀备考PPT之第一章概述(一)

    为了记录自己从2016.9~2017.1的<计算机网络>助教生涯,也为了及时梳理和整写笔记! 以上,是<计算机网络>课程的第一章概述.

  7. CentOS6安装各种大数据软件 第一章:各个软件版本介绍

    相关文章链接 CentOS6安装各种大数据软件 第一章:各个软件版本介绍 CentOS6安装各种大数据软件 第二章:Linux各个软件启动命令 CentOS6安装各种大数据软件 第三章:Linux基础 ...

  8. Camel In Action 阅读笔记 第一部分概述 + 第一章概述 认识Camel

    第一部分: 最开始的一小步 Apache Camel 是一个开源集成框架,其目的是让系统集成变得更加简便,在本书的第一章中,我们会为您介绍它并向您展示它是如何在大型企业应用中做好集成工作.您也会了解到 ...

  9. htt p第一章概述

    http的概述 1 web客户端与服务器是如何通信 2 web资源来自的何方 3 web事务是怎样的工作的 4 http通信所使用的报文结构 5 底层tcp的传输的结构 6不同的http协议体 什么是 ...

随机推荐

  1. 关于Cewu Lu等的《Combining Sketch and Tone for Pencil Drawing Production》一文铅笔画算法的理解和笔录。

     相关论文的链接:Combining Sketch and Tone for Pencil Drawing Production 第一次看<Combining Sketch and Tone f ...

  2. Hangfire入门(任务调度)

    一.简介 英文官网:http://hangfire.io/ 开源地址:https://github.com/HangfireIO Hangfire 不依赖于具体的.NET应用类型,包含.NET 和.N ...

  3. [LeetCode] Minimum Number of Arrows to Burst Balloons 最少数量的箭引爆气球

    There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided ...

  4. Hibernate 缓存机制浅析

    1. 为什么要用 Hibernate 缓存? Hibernate是一个持久层框架,经常访问物理数据库. 为了降低应用程序对物理数据源访问的频次,从而提高应用程序的运行性能. 缓存内的数据是对物理数据源 ...

  5. Goodbye 2016 总结与展望

    今天居然是2016年的最后一天了,写点什么回忆吧. 2016开始的时候我刚拿到普及组一等奖,还只是压线,水平很差.学校并不知道这有多差,于是狠狠宣传这所谓的"光荣事迹".那段时间我 ...

  6. JavaScript基础语法

    首先,JavaScript的基本语法是以名为ECMAScript的伪语言定义的,理解ECMAScript的细节就是理解它在浏览器中实现的关键,目前大多数浏览器都遵循了ECMAScript第3版的,但是 ...

  7. 【笔记】jstree插件的基本使用

    官网地址:https://www.jstree.com/ json返回参数格式:推荐第二种方式 不需要在重新拼接返回格式 不刷新页面重新初始化 jstree时使用:$.jstree.destroy() ...

  8. 使用css3做钟表

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  9. jQuery实现二级菜单

    <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...

  10. vmware Centos6.6安装64位

    Centos6.6安装64位 必须开启BIOS中的虚拟化技术 首先开机进入BIOS,一般机器是按F2,我的T420是按F1,然后进入Security,Virtualization,选择Enable即可 ...