accident <- read.csv("車禍.csv", fileEncoding = "big5")
camera <- read.csv("國道測速照相.csv", fileEncoding = "big5")
head(camera)
## road location lat lon
## 1 國道一號南向 1.95 323127.7 2777903
## 2 國道一號南向 22.70 304159.3 2773976
## 3 國道一號南向 30.00 297056.3 2774265
## 4 國道一號南向 60.13 271881.5 2762487
## 5 國道一號南向 68.15 266909.5 2756675
## 6 國道一號南向 78.20 258300.1 2753012
head(accident)
## road location
## 1 國道五號南向 36.3
## 2 國道三號南向 156.5
## 3 國道一號南向 5.0
## 4 國道一號北向 0.0
## 5 國道一號南向 9.0
## 6 國道二號東向 3.0
參數說明
- road: 國道x號x向
- location: xx.xx 公里
- range:差距幾公里
myf <- function(road, location, range){
# 計算測速照相機與車禍肇事地點之距離
dis1 <- ifelse(road %in% accident$road, 1, Inf)
dis2 <- abs(location - accident$location)
dis <- dis1 * dis2
# 計算距離小於 range (km) 的數目
count <- sum(dis < range)
return(count)
}
library(dplyr)
##
## Attaching package: 'dplyr'
##
## The following objects are masked from 'package:stats':
##
## filter, lag
##
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
# 計算離測速照相機 500m 以下的數目 (range = 0.5)
out <- camera %>% rowwise() %>%
mutate(count=myf(road, location, range = 0.5))
out
## Source: local data frame [100 x 5]
## Groups: <by row>
##
## road location lat lon count
## (fctr) (dbl) (dbl) (dbl) (int)
## 1 國道一號南向 1.95 323127.7 2777903 13
## 2 國道一號南向 22.70 304159.3 2773976 7
## 3 國道一號南向 30.00 297056.3 2774265 5
## 4 國道一號南向 60.13 271881.5 2762487 5
## 5 國道一號南向 68.15 266909.5 2756675 5
## 6 國道一號南向 78.20 258300.1 2753012 1
## 7 國道一號南向 102.45 246896.5 2736602 1
## 8 國道一號南向 124.00 235867.3 2720589 1
## 9 國道一號南向 126.54 235110.2 2718298 2
## 10 國道一號南向 152.90 224278.3 2696116 2
## .. ... ... ... ... ...
write.csv(out, "out.csv", row.names = F, quote = F)