rpostgis <- R + PostGIS

Today’s post is two in one: a PostgreSQL/PostGIS database and R. You’ll learn how to load and store vector data into a database in R. We’ll be using the rpostgis package for this, if you don’t have it you’ll need to install and initialize it (we’ve written about it before). Next, you need to connect to the database using the dbConnect function, specifying as arguments the driver for the database and the data to log in:

After creating the connection, proceed to import vector data from it. The pgGetGeom function is used for this purpose. For example, we will load the layer roads:

Let’s take a look at what we loaded:

The loaded roads layer has 1168 road segments. Now we will select the first 10 roads from our layer:

And let’s save the new layer in a new table using pgInsert specifying the connection to the database, the table name and the layer we want to save:

Now let’s load the saved table into a variable in R:

And let’s check how many objects it has:

The table has 10 linear objects. Saving works 🙂 At the end of our operations we still need to close the connection to the database with:

That’s it for today. We wish you a nice integration of R with the database.

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