3

Does anyone have a workflow for querying postgis data in R using the dplyr package?

R doesn't like the spatial columns in postgis data so can't read them in like a postgres table. I get the error message:

Warning message:
In postgresqlExecStatement(conn, statement, ...) :
  RS-DBI driver warning: (unrecognized PostgreSQL field type geometry (id:17846) in column 1)

I know there are other ways of reading in spatial data as all I want to do is join some data that have in R to an existing postgis table using R. I'm trying to avoid exporting it to a shapefile first.

3
  • 1
    What does dplyr have to do with Postgis ? Have a look at the rgdal and sp package to load spatial objects
    – Curlew
    Commented Jan 23, 2015 at 12:50
  • dplyr doesn't specifically have anything to do with postgis. It is what I wish to use to query my data. It basically just simplifies having to write SQL (something I'm not very good at) and from what I understand allows you to work directly on the database
    – marty_c
    Commented Jan 23, 2015 at 13:01
  • 1
    Where is your example of using dplyr in accessing and querying Postgis connections? What is the syntax behind your error? You have to provide enough information for us to recreate your problem. Commented May 3, 2017 at 2:39

1 Answer 1

5

You can load data from postgis with the rgdal package into R.

library(rgdal)
library(sp)

dbname = "yourdatabase"
host = "yourhost"
user = "AUser"
pass = "ThisUsersPassword"
name = "ASpatialTable" # Postgis table

dsn = paste0("PG:dbname='",dbname,"' host='",host,"' user='",user,"' password='",pass,"'")
res = readOGR(dsn,name)

plot(res)

Write yourself some function around it and you can use that in your dplyr pipes.

3
  • Hey Curlew, thanks for the response. I can load the data easily enough, but dplyr doesn't seem to like working with spatial data. I get the the following error when trying to work with it: Error in UseMethod("summarise") : no applicable method for 'summarise' applied to an object of class "c('SpatialPolygonsDataFrame', 'SpatialPolygons', 'Spatial')"...
    – marty_c
    Commented Feb 17, 2015 at 2:07
  • 1
    Why do you even think that dplyrs summarise would work on polygons? Try to convert it to a data.frame first (as.data.frame).
    – Curlew
    Commented Feb 17, 2015 at 8:56
  • To be honest I didn't think, it was very late at night! Thanks, as.data.frame works fine.
    – marty_c
    Commented Feb 18, 2015 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.