資料整理、新增變項

dta <- read.csv("Age_When_You_First_Had_Sex.csv",header = T)
head(dta)
##                          Date X1.1.2005
## 1    Age of first sex- Global      17.3
## 2     Age of first sex- India      19.8
## 3   Age of first sex- Vietnam      19.6
## 4 Age of first sex- Indonesia      19.1
## 5  Age of first sex- Malaysia      19.0
## 6    Age of first sex- Taiwan      18.9
head(gsub("Age of first sex- ","",dta[,1])) #gsub名字取代
## [1] "Global"    "India"     "Vietnam"   "Indonesia" "Malaysia"  "Taiwan"
dta$Country <- countrycode(dta[,1], "country.name", "iso3c")#將國家名稱換為iso3c型式
## Warning in countrycode(dta[, 1], "country.name", "iso3c"): Some values were not matched unambiguously: Age of first sex- Global, Age of first sex- Serbia & Montenegro
quantile(dta$X1.1.2005,probs = c(0.33,0.66))
##    33%    66% 
## 16.900 17.506
dta$age <- with(dta, cut(X1.1.2005,
breaks=c(15,16.9,17.5,20), labels=c("early","middle","late")))#將資料分為三個等級

head(dta)
##                          Date X1.1.2005 Country    age
## 1    Age of first sex- Global      17.3    <NA> middle
## 2     Age of first sex- India      19.8     IND   late
## 3   Age of first sex- Vietnam      19.6     VNM   late
## 4 Age of first sex- Indonesia      19.1     IDN   late
## 5  Age of first sex- Malaysia      19.0     MYS   late
## 6    Age of first sex- Taiwan      18.9     TWN   late

將資料結合地圖

mapDevice("x11")
Map <- joinCountryData2Map(dta, joinCode = "ISO3", nameJoinColumn = "Country")
## 40 codes from your data successfully matched countries in the map
## 2 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(Map, nameColumnToPlot = "age", 
               catMethod = "categorical", 
               addLegend= T,
               mapTitle =" ", 
               missingCountryCol = gray(.9), 
               colourPalette= c("dodgerblue", "deepskyblue","dodgerblue4"))