owned this note
owned this note
Published
Linked with GitHub
---
title: '台北市房價分析和視覺化使用R語言'
disqus: hackmd
---
台北市房價分析和視覺化使用R語言(作者陳寧寬)
===



## Table of Contents
[TOC]
先用此圖片來鎮樓~

## 讀取資料
首先我們可以從實價登錄的網站下載所需資料
[https://plvr.land.moi.gov.tw/DownloadOpenData]
1. 建議下載csv版本
2. 將資料放置getwd()函數告訴你的目錄中
3. 在getwd的目錄下新增一個資料夾叫作house,然後再解壓縮
會用到的package
---
```gherkin=
library(readr)
require(dplyr)
require(magrittr)
library(rgdal)#for fortify()
library(rgeos) #for fortify()
library(maptools) #for readShapeSpatial()
require(sf)
require(gridExtra)
library(viridis)
library(fields)
getwd()#使用getwd()函數來確認自己的預設目錄
```
```
taipei<- read_csv("~/house/A_lvr_land_A.csv")
colnames(taipei)
```
colnames 這個函數會秀出我們有何種feature
總共有27個X和一個Y(也就是房價)
我們讀進來後資料長得像是這樣

可以看出來R非常貼心的幫我們預設了colname但中文的colname並不方便,所以等一下還又去做一些處理
## 資料清洗
因為我們是要預測房價為主,但是實價登錄的資料其實是有五種交易類型
1. 土地
2. 車位
3. 房地(土地+建物)
4. 房地(土地+建物)+車位
5. 建物
所以這裡我們要藉助dplyr這個套件來幫忙塞選能用的交易個案,還有就是因為這些變數名稱實在是太長了所以我們把他們重新命名
```
featurename<- taipei[1,]
featurename <- as.character(featurename)
colnames(taipei)<-featurename
taipei <- taipei[-1,]
taipeiuse <- data.frame(type=as.factor(taipei$`transaction sign`),price=as.numeric(taipei$`total price NTD`),district=taipei$`The villages and towns urban district`,unit_price=as.numeric(taipei$`the unit price (NTD / square meter)`),building_area=as.numeric(taipei$`building shifting total area`))
taipeiuse$unit_price <- taipeiuse$price/taipeiuse$building_area
taipei1 <- arrange(taipeiuse,type,district,unit_price)
taipei1<- filter(taipei1,type=="房地(土地+建物)+車位"|type=="房地(土地+建物)")
taipeiuse$type
```
arrange函數是幫我們重新排序,排序依據依序是交易類型(type)和行政區(district)以及單位房價(unit_price)
filter函數則是幫我們塞選出可以用的交易態樣

由圖片中可以看出來會優先呈現出士林區的房價
## 資料的視覺化
這裡我們希望用不同的方式來作資料視覺化
首先是使用地理的方式視覺化
### 用台北市各個不同的行政區來視覺化每坪房價
```
taipei2 <- aggregate(3.305785*taipei1$unit_price, list(taipei1$district), mean)
taipei2
require(ggplot2)
taiwan.town.map<- st_read("TOWN_MOI_1080617.shp")
taipei.map <- taiwan.town.map[taiwan.town.map$COUNTYNAME == "臺北市",]
g1 <- ggplot(data = taipei.map) + geom_sf() + labs(title = "台北市行政區圖")
g3 <- ggplot(data = taipei.map) +
geom_sf(aes(fill = TOWNNAME), show.legend= F) +
geom_sf_text(aes(label = TOWNNAME), size = 3) +
labs(title = "台北市行政區圖")
my.taipei.map <- taipei.map[c("TOWNNAME", "geometry")]
my.taipei.map$TOWNNAME <- as.character(my.taipei.map$TOWNNAME)
#將資料合併 使用left join函數
my.taipei.map.data <- left_join(my.taipei.map,taipei2,
by= c("TOWNNAME"= "Group.1"))
g3
```
這裡使用st_read來讀取地圖資料
地圖資料則可以從政府的開放資料中下載
https://data.gov.tw/dataset/7441
```
#geom_sf的好處是可以更直覺的使用地圖的資料
g4 <- ggplot(data = my.taipei.map.data) +
geom_sf(aes(fill = x/10000))+
geom_sf_text(aes(label = TOWNNAME), size = 3) +
scale_fill_distiller(palette = "YlOrRd", direction = 1, name = "坪(萬)") +
labs(title="台北市各行政區房價分佈圖", x ="經度", y = "緯度")
g4
#diredtion =1 由小到大的房價會由淺到深 =-1則相反
```

這裡我們可以看出台北市的房價是以大安區最高每坪超過80萬元
整個台北市大致呈現內高外低的趨勢,之後會再慢慢補上如何預測房價跟其他視覺化房價的方法
###### tags: `R` `房價預測` `地理繪圖`