Hello ! I am trying to learn spatial data viz in R and I found this tutorial (and associated book chapter) on Github: sdvwR. I am trying to follow the instructions: load an .shp file called "world" (I downloaded the zip from Github and saved on my desktop) and change the coordinate system:
so far so good. Then I need to transform it as to be able to be used by ggplot and then merge it with the @data part of the spatialPolygonsDataFrame. The code I found on github used fortify():
but I am not able to use it and to my understanding it is better to use tidy form the broom package, but I cannot make it work:
wrld.rob.f <- tidy(wrld.rob, region = "sov_a3" )
using "sov_a3" as region results in an error message, and if I do not use anything, a dataframe is created but then I am not able to merge it with the initial @data part, as there is no common column between the two data frames.
Does someone have an idea of how I can solve this issue?
Thanks
V.
Hi Vivvi, the tutorial you link is seven years old, and the techniques are no longer best practice.
The package {sp} was superseded by {sf}, with somewhat different workflow, and ggplot2::fortify() is no longer necessary for plotting spatial objects; the use case is nowadays handled via a ggplot2::geom_sf() call.
The steps necessary for your use case in current package environment would be slightly different:
read the data in via sf::st_read()
change projection via sf::st_transform()
join the data via dplyr::left_join() or dplyr::inner_join() as appropriate
plot via base plot, or ggplot2::geom_sf()
I am aware that this is a big bite to digest when just starting out, and I suggest that you have look at the excellent Geocomputation with R book; it is available online for free and it was written by the same Robin Lovelace as your original tutorial.
Thank you @jlacko !
I figured that there were some outdated info, but I hadn't get to which extent! I will follow your suggestion and head to the Geocomputation with R book! Yes, starting out can be quite overwhelming!
Thanks again!
I can imagine that... The good news is that while the workflow is different now than then it feels much easier. I have done both, so I feel to be in a position to compare.
The {sp} objects used to be sui generis S3 objects with data dimension in the @data slot, which behaved sorta kinda like a regular data frame (except when not). The {sf} objects are modified data frames from start, with only a single special column that contains geometry. They accept all methods of data.frame, and the use case of your original post - joining new data by a polygon id - is actually one of the strong points of the new workflow.
You will be fine (even if it takes a while to master the techinques).