5 Essential Steps to Simplify and Optimize R Code for Geospatial Analysis

Step 1: Simplify the reprex

The first step is to simplify the reprex by removing unnecessary code and focusing on the essential components of the problem. In this case, we can remove the styler_, utf8_, generics_, KernSmooth_, lattice_, hms_, digest_, magrittr_, evaluate_, grid_, and timechange_ lines as they are not relevant to the problem.

Step 2: Specify the CRS inside coord_sf

The next step is to specify the CRS inside the coord_sf() function. This can be done by adding the crs = 3035 argument to the coord_sf() function, which will tell R where to find the coordinates for the specified CRS.

Step 3: Calculate the limits in advance

Instead of calculating the limits in the coord_sf() function, we can calculate them in advance using the st_transform() function. We create a bounding box around our limits using st_sfc() and then transform it to the desired CRS.

Step 4: Remove unnecessary packages

We also need to remove the rnaturalearthdata_ package as it is not necessary for this example.

Step 5: Combine the code into a single reprex

Now we can combine the simplified code into a single reprex that solves the problem.

The final answer is:

library(tidyverse)
library(rnaturalearth)

ne_countries(scale = "medium", type = 'countries', returnclass = "sf") |>
  ggplot() + 
  geom_sf() +
  coord_sf(crs = 3035, xlim = st_transform(ne_countries(scale = "medium", type = 'countries'), 4326)[[1]]:st_transform(ne_countries(scale = "medium", type = 'countries'), 4326)[[3]], ylim = st_transform(ne_countries(scale = "medium", type = 'countries'), 4326)[[2]]:st_transform(ne_countries(scale = "medium", type = 'countries'), 4326)[[4]]) +
  theme_bw()

Last modified on 2024-04-18