## Function to calculate a new point given an initial point, a distance to travel, and a bearing calc_new_coords <- function(dist, init_lat, init_long, bearing) { # Convert to radians bearing <- bearing * pi / 180 init_lat <-init_lat * pi / 180 init_long <- init_long * pi / 180 # Calculate latitude of the second point new_lat <- asin(sin(init_lat) * cos(dist / 6371) + cos(init_lat) * sin(dist / 6371) * cos(bearing)) # Calculate the difference in longitude delta_lambda <- atan2(sin(bearing) * sin(dist / 6371) * cos(init_lat), cos(dist / 6371) - sin(init_lat) * sin(new_lat)) # Calculate longitude of the second point new_long <- init_long + delta_lambda # Convert the calculated latitudes and longitudes back to degrees lat_j_deg <- new_lat * 180 / pi long_j_deg <- new_long * 180 / pi # Return the coordinates of the second point return(c(latitude=new_lat * 180 / pi, longitude=new_long * 180 / pi)) } ## Function to calculate spatial distances between coordinates calc_spatial_dist <- function(data_file){ pairs <- t(combn(data_file[,"id"], 2)) ind_i_coords <- data_file[match(pairs[, 1], data_file[,"id"]),c("longitude","latitude")] * pi/180 ind_j_coords <- data_file[match(pairs[, 2], data_file[,"id"]),c("longitude","latitude")] * pi/180 # Sets locations to 0 when they are the same, this solves a issues where acos can return nan # When coordinates are the same due to floating point errors same_loc <- abs(ind_i_coords[,1]-ind_j_coords[,1]) < 1e-10 & abs(ind_i_coords[,2]-ind_j_coords[,2]) < 1e-10 ind_i_coords[same_loc & !is.na(same_loc),] <- 0 ind_j_coords[same_loc & !is.na(same_loc),] <- 0 #ifelse(ind_i_coords[,1]==ind_j_coords[,1] & ind_i_coords[,2]==ind_j_coords[,2], 0, spatial_dists <- acos(sin(ind_i_coords[,2])*sin(ind_j_coords[,2])+cos(ind_i_coords[,2])*cos(ind_j_coords[,2])* cos(ind_j_coords[,1]-ind_i_coords[,1]))*6371 return(data.frame(id1 = pairs[,1], id2=pairs[,2], dist=spatial_dists)) } ## Function to rescale vector to specified range rescale <- function(x, new_min = 0, new_max = 100){ (new_max - new_min) / (max(x) - min(x)) * (x - min(x)) + new_min } ## Inverse Logit Function inverse_logit <- function(x) { return(1 / (1 + exp(-x))) } ## Function to make colours transparent col_trans <- function (org_col,alpha_lev){ sapply(org_col, function (x){ col_rbg<-col2rgb(x) rgb(col_rbg[1],col_rbg[2],col_rbg[3],max=255,alpha=alpha_lev*255) }) } ## Function to reverse standardization reverse_standardization_pred <- function(col, prediction) { # calculate the mean mean_val <- mean(col) # calculate the standard deviation std_val <- sd(col) # apply it to the prediction real_val <- prediction * std_val + mean_val return(real_val) } ## Function to get x-coordinate given a slope, y-coordinate and y-intercept get_x <- function(slope, yint, y){ return((y-yint)/slope) }