In-Class Exercise

Q1

Indicate countries you have visited so far on a world map in the style of the ebola outbreaks example.

library(rworldmap)
## Loading required package: sp
## ### Welcome to rworldmap ###
## For a short introduction type :   vignette('rworldmap')
dta1 <- read.table("C:/Users/TheorEco Lab/Desktop/108-2/DataManagement/0518/visit_country.txt", h = T)

library(countrycode)

# a data.frame with the ISO3 country names plus a variable to
# merge to the map data
dta1$Country <- countrycode(dta1[,1], "country.name", "iso3c")
dta1$visit <- rep(1, length(dta1$Country))

mapDevice("x11")

# join the data.frame to the country map data
visitMap <- joinCountryData2Map(dta1, joinCode = "ISO3", nameJoinColumn = "Country")
## 3 codes from your data successfully matched countries in the map
## 0 codes from your data failed to match with a country code in the map
## 240 codes from the map weren't represented in your data
# plot it, the color palette's first color is red
mapCountryData(visitMap, nameColumnToPlot = "visit", catMethod = "categorical",
               addLegend = FALSE, mapTitle =" ", missingCountryCol = gray(.9))

Q2

Plot places in administratice areas of Taiwan you have visited so far.

dta2 <- sf::st_read("C:/Users/TheorEco Lab/Desktop/108-2/DataManagement/0518/TWN_adm2.shp")
## Reading layer `TWN_adm2' from data source `C:\Users\TheorEco Lab\Desktop\108-2\DataManagement\0518\TWN_adm2.shp' using driver `ESRI Shapefile'
## Simple feature collection with 22 features and 11 fields
## geometry type:  MULTIPOLYGON
## dimension:      XY
## bbox:           xmin: 116.71 ymin: 20.6975 xmax: 122.1085 ymax: 25.63431
## geographic CRS: WGS 84
str(dta2)
## Classes 'sf' and 'data.frame':   22 obs. of  12 variables:
##  $ ID_0     : num  225 225 225 225 225 225 225 225 225 225 ...
##  $ ISO      : Factor w/ 1 level "TWN": 1 1 1 1 1 1 1 1 1 1 ...
##  $ NAME_0   : Factor w/ 1 level "Taiwan": 1 1 1 1 1 1 1 1 1 1 ...
##  $ ID_1     : num  1 2 3 4 4 4 4 4 4 4 ...
##  $ NAME_1   : Factor w/ 4 levels "Kaohsiung","Pratas Islands",..: 1 2 3 4 4 4 4 4 4 4 ...
##  $ ID_2     : num  1 2 3 4 5 6 7 8 9 10 ...
##  $ NAME_2   : Factor w/ 21 levels "Changhwa","Chiayi",..: 7 NA 18 1 2 3 4 5 6 8 ...
##  $ TYPE_2   : Factor w/ 3 levels "Chuan-shih","District|Hsien",..: 1 NA 1 2 2 2 2 2 2 3 ...
##  $ ENGTYPE_2: Factor w/ 3 levels "County","Municipality",..: 3 NA 3 1 1 1 1 1 1 2 ...
##  $ NL_NAME_2: Factor w/ 0 levels: NA NA NA NA NA NA NA NA NA NA ...
##  $ VARNAME_2: Factor w/ 16 levels "Gaoxiong","Gaoxiong Shi",..: 2 NA 8 16 4 13 3 14 1 5 ...
##  $ geometry :sfc_MULTIPOLYGON of length 22; first list element: List of 2
##   ..$ :List of 1
##   .. ..$ : num [1:4, 1:2] 120.2 120.2 120.2 120.2 22.8 ...
##   ..$ :List of 1
##   .. ..$ : num [1:827, 1:2] 120 120 120 120 120 ...
##   ..- attr(*, "class")= chr  "XY" "MULTIPOLYGON" "sfg"
##  - attr(*, "sf_column")= chr "geometry"
##  - attr(*, "agr")= Factor w/ 3 levels "constant","aggregate",..: NA NA NA NA NA NA NA NA NA NA ...
##   ..- attr(*, "names")= chr  "ID_0" "ISO" "NAME_0" "ID_1" ...
dta2$NAME_2
##  [1] Kaohsiung City <NA>           Taipei City    Changhwa       Chiayi        
##  [6] Hsinchu        Hualien        Ilan           Kaohsiung      Keelung City  
## [11] Miaoli         Nantou         Penghu         Pingtung       Taichung City 
## [16] Taichung       Tainan City    Tainan         Taipei         Taitung       
## [21] Taoyuan        Yunlin        
## 21 Levels: Changhwa Chiayi Hsinchu Hualien Ilan Kaohsiung ... Yunlin
dta2$visited <- c("red", "lightgray", "red", "lightgray", "lightgray", "red", 
                  "lightgray", "red", "red", "lightgray", "lightgray", "lightgray", 
                  "red", "red", "red", "red", "red", "red", 
                  "red", "red", "lightgray", "lightgray")
plot(dta2, col = dta2$visited, max.plot = 1, main = "")
legend("topleft", inset=.02, c("have visited", "haven't visited"), fill=c("lightgray","red"))

Q3

Map an area of Tainan city to include three of your favorite places to eat as landmarks.

dta3 <- list(lat = c(22.998402, 23.004596, 23.005070, 23.005013,22.983063, 22.990121),
             lng = c(120.233564, 120.221126,  120.222829, 120.218745, 120.205673, 120.233056),
             loc = c("生命樹咖啡", "小邁時光", "濰克早午餐(長榮店)", "芯恬也咖啡早午餐","城南舊肆", "誠品生活南紡店"))
library(leaflet)
m <- leaflet() %>%
 addTiles() %>%  
 addMarkers(lng = dta3$lng, 
            lat = dta3$lat, 
            popup = dta3$loc)
m

Exercise

Q1

Build a thematic plot of the results of Taiwan 2020 presidential election between the DDP and the KMT. The geographical data (maps) for Taiwan can be obtained from DIVA-GIS: Geographic Information System for Biodiversity Research.

Source: Taiwan presidential election 2020 . Wikipedia.

dta3 <- sf::st_read("C:/Users/TheorEco Lab/Desktop/108-2/DataManagement/0518/TWN_adm2.shp")
## Reading layer `TWN_adm2' from data source `C:\Users\TheorEco Lab\Desktop\108-2\DataManagement\0518\TWN_adm2.shp' using driver `ESRI Shapefile'
## Simple feature collection with 22 features and 11 fields
## geometry type:  MULTIPOLYGON
## dimension:      XY
## bbox:           xmin: 116.71 ymin: 20.6975 xmax: 122.1085 ymax: 25.63431
## geographic CRS: WGS 84
dta3$NAME_2
##  [1] Kaohsiung City <NA>           Taipei City    Changhwa       Chiayi        
##  [6] Hsinchu        Hualien        Ilan           Kaohsiung      Keelung City  
## [11] Miaoli         Nantou         Penghu         Pingtung       Taichung City 
## [16] Taichung       Tainan City    Tainan         Taipei         Taitung       
## [21] Taoyuan        Yunlin        
## 21 Levels: Changhwa Chiayi Hsinchu Hualien Ilan Kaohsiung ... Yunlin
dta3$votes <- c(62.2, 0, 53.7, 57.2, 64.2, 47.5, 
                60.4, 63.3, 62.2, 50.8, 50.3, 50.8, 
                53.9, 62.2, 57.0, 57.0, 67.4, 67.4, 
                56.5, 58.3, 54.8, 61.6)
dta3$color <- c("green", "gray", "green", "green", "green", "blue", 
                "blue", "green", "green", "green", "blue", "green", 
                "green", "green", "green", "green", "green", "green", 
                "green", "blue", "green", "green")
plot(dta3, col = dta3$color, max.plot = 1, main = "")
legend("topleft", inset=.02, c("Tsai Ing-wen,
William Lai", "Han Kuo-yu,
Chang San-cheng"), fill=c("green","blue"))

Q2

Traffic accidents on roads in Taiwan in 2011 is available on-line from the Department of Transportation. Plot the number of deaths per 10,000 vehicles over the administrative units.

Data not available

Q3

DownloDownload the data for age fisrt have sex across several countries to make the following plot:

dta4 <- read.csv("C:/Users/TheorEco Lab/Desktop/108-2/DataManagement/0518/Age_When_You_First_Had_Sex.csv", header = TRUE)
str(dta4)
## 'data.frame':    41 obs. of  2 variables:
##  $ Country: Factor w/ 41 levels "Australia","Austria",..: 17 41 18 23 36 15 30 7 21 37 ...
##  $ Age    : num  19.8 19.6 19.1 19 18.9 18.6 18.4 18.3 18.1 18 ...
library(choroplethr)
country_choropleth(dta4, 
       num_colors = 9) +
  scale_fill_brewer            (palette="Blues") +
  labs(title=" Age When You First Had Sex")

Error: Package choroplethrMaps is needed for this function to work. Please install it.

不知道 function loading 哪裡有問題,無法使用老師上課示範的方法,以下參照廖同學的做法。

library(countrycode)
dta4_maps <- data.frame(Country = countrycode(dta4$Country,"country.name", "iso3c"),
                        Age = dta4$Age)
## Warning in countrycode(dta4$Country, "country.name", "iso3c"): Some values were not matched unambiguously: Serbia & Montenegro
library(rworldmap)
dta4Map <- joinCountryData2Map(dta4_maps, joinCode = "ISO3", nameJoinColumn = "Country")
## 40 codes from your data successfully matched countries in the map
## 1 codes from your data failed to match with a country code in the map
## 203 codes from the map weren't represented in your data
mapCountryData(dta4Map, nameColumnToPlot = "Age", catMethod = 'pretty',
               addLegend = FALSE, missingCountryCol = gray(.9), mapTitle = '',
               colourPalette = c('skyblue1', 'skyblue2', 'dodgerblue', 'dodgerblue4', 'black'))
## You asked for 7 categories, 9 were used due to pretty() classification
## Warning in rwmGetColours(colourPalette, numColours): 5 colours specified and 9
## required, using interpolation to calculate colours

Q4

Download all the files from github (click the downward triangle in the clone or download button in green) for flood in schools in Taipei to replicate the analysis with the markdown file included.

台北市國民小學洪災分析

降雨頻率分析與淹水潛勢是洪災分析重要的資料來源,利用水文分析進行降雨觀測及淹水分析結果,進一步整合社會統計資料,可評估人類社會承受災害的潛在風險。

假設將24小時延時200年重現期降雨的淹水潛勢的深度達50cm以上的區域,定義為「潛在受災區」。

1.設定所需的函式庫(libraries)

install.packages("rgdal")   #讓R可以認識shp file
install.packages("sp")
library(rgdal)
## rgdal: version: 1.4-8, (SVN revision 845)
##  Geospatial Data Abstraction Library extensions to R successfully loaded
##  Loaded GDAL runtime: GDAL 2.2.3, released 2017/11/20
##  Path to GDAL shared files: C:/Users/TheorEco Lab/Documents/R/win-library/3.6/rgdal/gdal
##  GDAL binary built with GEOS: TRUE 
##  Loaded PROJ.4 runtime: Rel. 4.9.3, 15 August 2016, [PJ_VERSION: 493]
##  Path to PROJ.4 shared files: C:/Users/TheorEco Lab/Documents/R/win-library/3.6/rgdal/proj
##  Linking to sp version: 1.4-1
library(sp)

setwd("C:/Users/TheorEco Lab/Desktop/108-2/DataManagement/0518/flood-in-school-master")  #設定working area

Flood <- readOGR(dsn = ".", layer = "flood50", encoding="big5")
## OGR data source with driver: ESRI Shapefile 
## Source: "C:\Users\TheorEco Lab\Desktop\108-2\DataManagement\0518\flood-in-school-master", layer: "flood50"
## with 5103 features
## It has 5 fields
# dsn = “.“ 是路徑,但因我們已將working area設定完成,所以打.就好
# dsn 是指路徑
# layer 是指shp的名稱
Schools <- readOGR(dsn = ".", layer = "tpecity_school", encoding="big5")
## OGR data source with driver: ESRI Shapefile 
## Source: "C:\Users\TheorEco Lab\Desktop\108-2\DataManagement\0518\flood-in-school-master", layer: "tpecity_school"
## with 198 features
## It has 3 fields
## Integer64 fields read as strings:  STUDENTS
Schools.Flood <- Schools[Flood, ] #把學校落在Flood中的排出來

2.疊三個圖層

plot(Flood, col='cyan')
plot(Schools, col='gray', pch=20, add=TRUE)
plot(Schools.Flood, col='red', pch=20, add=TRUE)

nrow(Schools.Flood)
## [1] 36
#把36筆排出來
# 把 Schools.Flood 中計算筆數 (本例有36筆)
head(Schools.Flood, n=36)
##             coordinates                   TEXTSTRING   ID STUDENTS
## 1   (301759.8, 2776380)             憯急\x9e\x9c葉    1       95
## 2   (301866.4, 2776287)       憯急\x9e\x9c\xb0\x8f    2       93
## 8   (301387.6, 2777951)       \xe6\x98噸\xe5\x9c葉   33      113
## 9   (301094.7, 2777716)  \xe6\x96\x9e\x9c\xb0\x8f   39      213
## 13  (297797.9, 2777667)        撖\xae\x9c\xb0\x8f   48       63
## 26  (302358.7, 2778549)       憯急\xe5\x9c\xb0\x8f  300       52
## 42  (309784.9, 2775764)       憭扳\xb9\x9c\xb0\x8f  681       92
## 52  (301512.1, 2775618)        \xe7朣∪\x9c\xb0\x8f  730      163
## 61  (308530.7, 2773620)        \xe6皝\x9c\xb0\x8f  837       24
## 67  (306388.8, 2772734)              瘞\x94\x9c葉  849       35
## 72    (304217, 2772849)            銝剖控\xe5\x9c葉  863      200
## 73  (303883.8, 2773194)             鈭虜\xe5\x9c葉  864       91
## 74  (303560.9, 2773155)       鈭虜\xe5\x9c\xb0\x8f  865       55
## 75  (302584.5, 2772046)  \xe5\x90\x9e\x9c\xb0\x8f  882       91
## 78  (301662.6, 2774893) \xe5\x8a蔬\xe5\x9c\xb0\x8f  903      204
## 80  (301096.9, 2772347)  \xe8\xe8\x90\x9c\xb0\x8f  913      119
## 81  (301075.9, 2772803)  \xe9\x9b\xe5\x9c\xb0\x8f  915       24
## 82  (301247.5, 2772141)  \xe6\xe6\xe5\x9c\xb0\x8f  916      201
## 83  (301079.5, 2773162)              瘞\xac\x9c葉  917      186
## 84  (301239.9, 2773257)       憭批\x90\x9c\xb0\x8f  918       25
## 87  (300894.4, 2772864)      憭芸像\xe5\x9c\xb0\x8f  924       91
## 89  (300805.4, 2773077)       憭扳\xa9\x9c\xb0\x8f  926      161
## 91    (298621, 2769869)        \xe8瘙\x9c\xb0\x8f  979       99
## 98  (299149.1, 2769994)       樴控\xe5\x9c\xb0\x8f 1051       87
## 100   (304810, 2770048)        隞\x84\x9c\xb0\x8f 1059       56
## 101 (304749.5, 2770157)              隞\x84\x9c葉 1060      133
## 106 (303073.2, 2772220)  \xe9\xe6\xe5\x9c\xb0\x8f 1085       48
## 119   (307068, 2771434)             瘞詨\x90\x9c葉 1199      101
## 123   (306471, 2764691)        \xe6\xe6\xe5\x9c葉 1247      118
## 124 (306449.8, 2764558)         \xe5\x9c\x85\x8a 1248       68
## 131 (304921.7, 2766373)  \xe8\x88\x9a\x9c\xb0\x8f 1276       63
## 134 (304240.7, 2769283)       撱箏\xae\x9c\xb0\x8f 1287       43
## 138 (302582.5, 2770855)        敹\xad\x9c\xb0\x8f 1306      152
## 149 (299478.7, 2769410)  \xe9\x9b\x9c\x9c\xb0\x8f 1362      110
## 174 (304714.8, 2766624)        \xe8\x88\xa6\x9c葉 1575       85
## 175 (303576.3, 2765485)       皞芸\xe5\x9c\xb0\x8f 1576      168
sum(as.integer(Schools.Flood$STUDENTS)) # sum 計算Schools.Flood中學生總數為多少
## [1] 2645