Skip to content

Commit

Permalink
Merge pull request #683 from iod-ine/exercises
Browse files Browse the repository at this point in the history
Modify an example in ch4 and add a solution
  • Loading branch information
Nowosad committed Nov 28, 2021
2 parents 5dd7cf2 + 082e25f commit c372733
Showing 1 changed file with 23 additions and 7 deletions.
30 changes: 23 additions & 7 deletions _04-ex.Rmd
Original file line number Diff line number Diff line change
Expand Up @@ -111,11 +111,27 @@ two_rasts_df = as.data.frame(two_rasts)
cor(two_rasts_df$ndvi, two_rasts_df$ndwi)
```

E7. A StackOverflow [post](https://stackoverflow.com/questions/35555709/global-raster-of-geographic-distances) shows how to compute distances to the nearest coastline using `raster::distance()`.
Retrieve a digital elevation model of Spain, and compute a raster which represents distances to the coast across the country (hint: use `geodata::elevation_30s()`).
Note: it may be wise to increase the cell size of the input raster to reduce compute time during this operation.

<!--toDo:jn-->
<!--improve/replace/modify the following q-->
<!-- E7. A StackOverflow [post](https://stackoverflow.com/questions/35555709/global-raster-of-geographic-distances) shows how to compute distances to the nearest coastline using `raster::distance()`. -->
<!-- Retrieve a digital elevation model of Spain, and compute a raster which represents distances to the coast across the country (hint: use `getData()`). -->
<!-- Second, use a simple approach to weight the distance raster with elevation (other weighting approaches are possible, include flow direction and steepness); every 100 altitudinal meters should increase the distance to the coast by 10 km. -->
<!-- Finally, compute the difference between the raster using the Euclidean distance and the raster weighted by elevation. -->
<!-- Note: it may be wise to increase the cell size of the input raster to reduce compute time during this operation. -->
```{r}
# Fetch the DEM data for Spain
spain_dem = geodata::elevation_30s(country = "Spain", path = ".", mask = FALSE)
# Reduce the resolution by a factor of 20 to speed up calculations
spain_dem = aggregate(spain_dem, fact = 20)
# According to the documentation, terra::distance() will calculate distance
# for all cells that are NA to the nearest cell that are not NA. To calculate
# distance to the coast, we need a raster that has NA values over land and any
# other value over water
water_mask = is.na(spain_dem)
water_mask[water_mask == 0] = NA
# Use the distance() function on this mask to get distance to the coast
distance_to_coast = distance(water_mask)
# Plot the result
plot(distance_to_coast, main = "Distance to the coast")
```

0 comments on commit c372733

Please sign in to comment.