前幾章對R語言的運行原理、基本語法、數據類型、環境部署等基礎知識做了簡單介紹,本節將結合具體案例進行驗證測試。 案例場景:從互聯網下載全國三甲醫院數據,以地圖做爲背景,展示各醫院在地圖上的分佈圖。全國三甲醫院數據來源 http://www.wxmp.cn/cms/detail-51610-23480-1.htmlhtml
目錄:jquery
map包研究:linux
效果圖:git
數據清洗:github
#讀取數,刪除空值 pdata<-read.csv("d:\\data.txt",sep="\t",header=FALSE,col.names = c("city","name")) pdata <- na.omit(pdata) #加載baidumap 根據名稱獲取醫院經緯度 library(baidumap) bhs <- getCoordinate(pdata$name,formatted = T) #組織清洗後的數據 hsdata <- data.frame(name=rownames(bhs),lon=bhs[,1],lat=bhs[,2]) result <- merge(pdata,hsdata,by.x="name",by.y="name") head(result) #刪除空值數據 result <- na.omit(result) #保存清空後的數據 path <- c("d:\\data1.txt") write.table(result,file = path,row.names = FALSE)
清理先後的數據對比圖以下:web
R包開發:瀏覽器
#FastRWeb調用R腳本函數入口 run <- function(...){ #物理文件保存地址 path = c("/var/www/html") file_name = paste0("C", format(Sys.time(), "%Y%m%d")) full_path = paste0(path, "/", file_name, ".html") if (file.exists(full_path)) { out(file_name) return } my.writeMap(full_path) out(file_name) } my.writeMap <- function(file_name){ #獲取清洗完成的數據 pdata<-read.csv("/var/www/html/data1.txt",sep="\t",header=FALSE,col.names = c("name","cityName","lon","lat")) head(pdata) #按城市統計醫院數量(分佈圖用到的參數) cityCount <- tapply(pdata$name,pdata$cityName,length) citydata <- data.frame(place=row.names(cityCount),values=cityCount) #geodata stadata <- data.frame(lon=pdata$lon,lat=pdata$lat,cityname = pdata$name) #分佈圖 library(REmap) output <- remapC(citydata, title = "Demo", theme = get_theme("Bright"), markPointData =stadata[,3], markPointTheme = markPointControl(symbol = "pin",effect = TRUE,symbolSize = 3,color = "red"), geoData = stadata) my.plot(output,file_name) } #寫物理文件,修改REmap 代碼 my.plot <- function(object, file_name) { ## SVG rewrite JS path if (object@maptype == 'SVG') { content <- sub("http://echarts.baidu.com/build/dist/echarts.js","./js/echarts.js", object@content) content <- sub("http://echarts.baidu.com/build/dist/echarts-all.js","./js/echarts-all.js",content) } if (object@maptype == 'SVGH') { content <- sub("http://echarts.baidu.com/build/dist/echarts.js","./js/echarts.js", object@content) content <- sub("http://echarts.baidu.com/build/dist/echarts-all.js","./js/echarts-all.js",content) } ## Bmap rewrite JS path if (object@maptype == "Bmap") { content <- sub("http://echarts.baidu.com/build/dist/echarts.js","./js/echarts.js",object@content) content <- sub("http://echarts.baidu.com/doc/asset/js/jquery.min.js","./js/jquery.min.js",content) content <- sub("http://lchiffon.github.io/reveal_slidify/echarts/require", "./js",content) } writeLines(content,file_name,useBytes = T) }
R腳本部署:app