Calculating distances in R

How to calculate distances in R. This script will:

  • Read an online CSV file with hospital coordinates
  • Remove a few attributes
  • Convert the hospital coordinates to geometry (points)
  • Create a new point
  • Calculate the distance from each hospital to the separate point
  • Plot the points on a map using tmap
  • Create a simple plot with the distances
# Load libraries
library(dplyr)
library(ggplot2)
library(mapview)
library(sf)
library(units)

# Read GeoPackage with hospitals
hospitals_csv = read.csv("https://vgregion.entryscape.net/store/7/resource/39", sep=',')

# Remove a few attributes from hospitals
hospitals_csv = select(hospitals_csv, namn, xkoord, ykoord)

# Coordinates --> spatial data (EPSG = 3006)
hospitals_points = st_as_sf(hospitals_csv, coords = c("ykoord", "xkoord"), crs = 3006)

# Create point and define coordinate system (3006)
point <- st_point(c(439122,6449521))     # Coordinates for Tidaholm, Västra Götaland
point = st_sfc(point, crs = "EPSG:3006") # Set point to SWEREF 99 TM

# Calculate distance between each hospital and the point
hospitals_points$distance = st_distance(hospitals_points, point)          # Create the attribute distance
hospitals_points$distance = round(hospitals_points$distance, digits = 0)  # Round distance

# View result on web map for validation
mapview(hospitals_points, col.regions = "red", cex = 6, label = 'namn') + mapview(point)

# Create plot of distance to each hospital
plot = ggplot(data = hospitals_points) + 
  geom_point(mapping = aes(x = namn, y = distance))

plot
plot + theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))   # Set angle for x axis test

The resulting plot with distance to each hospital:

Leave a Reply

Your email address will not be published. Required fields are marked *

Please reload

Please Wait