-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.R
62 lines (52 loc) · 2.14 KB
/
functions.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
DatasetToFeather <- function(fileName = 'ships'){
data <- as_tibble(fread(paste0(fileName, '.csv'), header = T))
write_feather(data, paste0(fileName, '.feather'))
}
summarizeDistance <- function(data,
ShipType = input$vt_selected,
VesselName=input$vessels_selected,
method = input$method){
target_obs <- data %>%
dplyr::filter(ship_type == ShipType & SHIPNAME == VesselName ) %>%
dplyr::arrange(DATETIME) %>%
dplyr::mutate(id = row_number())
target_obs <- getDistance(data = target_obs,
targetcolumns = c("LON", "LAT"),
method = method)
mostRecent <- target_obs %>%
dplyr::slice(which.max(DISTANCE)) %>%
dplyr::filter(row_number() == n())
mostRecent <- rbind(mostRecent, target_obs[target_obs$id == (mostRecent$id + 1),])
obs <- list(mostRecent=mostRecent, target_obs= target_obs)
return(obs)
}
getDistance <- function(data, targetcolumns = c("LON", "LAT"),
method = "Euclidean"){
if( method == 'Euclidean' ){
data$DISTANCE <- sapply(seq_len(nrow(data)), function(x){
objDist <- distm(data[x,targetcolumns], data[(x + 1),targetcolumns])
})}
if( method == 'Haversine' ){
data$DISTANCE <- sapply(seq_len(nrow(data)), function(x){
objDist <- distm(data[x,targetcolumns], data[(x + 1),targetcolumns],
fun=distHaversine)
})}
if( method == 'Rasters' ){
pts2<-st_as_sf(data[,c("LON", "LAT")], coords = c("LON", "LAT"),
crs = 'WGS84')
r <- raster(extent(pts2), resolution=0.01)
crs(r) <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0"
rtas <- fasterize(summarize(world), r)
data$DISTANCE <- sapply(1:nrow(data), function(x){
rtas_pts <- rtas
xy <- st_coordinates(pts2[c(x,x+1),])
icell <- cellFromXY(rtas, xy)
rtas_pts[icell[1]] <- 2
tryCatch({
d <- gridDistance(rtas_pts, origin = 2,omit = 1)
d[icell[2]]
}, error=function(e){0})
})
}
return(data)
}