Loading and saving spatial vector layers in R

Analyzes on spatial data cannot be performed without loading them into R. The library rgdal is used for this purpose. Install and initialize this library in RStudio. The readOGR function is used to load a vector layer into a variable. To read, the path of the folder where the file is located and its name without extension must be specified (the districts file used in this exercise is from Polish National Register of Borders, you can downloaded them for free here):

The loaded layer can be displayed in a window using the plot function as for rasters:

The layer just loaded is displayed.

r_shp1

The loaded layer contains a table with descriptive attributes that can be called with the command:

We display the entire contents of the DBF table associated with the geometry. We can display the first six rows with:

We can display the values stored in a particular column of the districts@data table using the expression variable@data$column_name, for example:: districts@data$jpt_nazwa_ 

This command displays the district names stored in the jpt_nazwa_

We can display the values stored in a particular row of the districts@data by using the expression variable@data$[row_number,], for example:

Now let’s select powiat pruszkowski from our set and display it. First we write the number of the row containing our county into the select variable by using the which function:

Display the value of the select variable in the console:

Now we store object 23 from the entire set in the district variable, using the row-specific select option described above. In this case, we select a district from the districts variable using the previously designated select variable:

Display the result:

r_shp2

Now we want to save the result to a shape file. This is done with the function writeOGR, in which we must define at least four attributes in this form:

In our example, this would look like this:

The file is saved to disk and we can use it in other programs or processing. The described functions have the possibility to define many detailed parameters. The knowledge about these parameters can be found in the help or in the R documentation.

Leave a Reply

Your email address will not be published.

Translate using Google Translate»
Social media & sharing icons powered by UltimatelySocial

Podoba Ci się nasza strona? Odwiedź nasz profil