Last active
August 2, 2018 20:39
-
-
Save ateucher/7bbbf70e2cfad8a3db3e4f142ef44c96 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
title: "PostGIS+sf+Rmarkdown" | |
output: html_document | |
--- | |
Use `bash` chunk to execute commands | |
```{bash message=FALSE, eval=FALSE} | |
createdb test123 -U postgres | |
psql -d test123 -U postgres -c "CREATE EXTENSION postgis;" | |
``` | |
Connect to the database with R, and write some data: | |
```{r message=FALSE} | |
library(sf) | |
library(DBI) | |
library(RPostgres) | |
library(mapview) | |
library(sp) | |
data(meuse) | |
pts <- st_as_sf(meuse, coords = c("x", "y"), crs = 28992) | |
pg <- DBI::dbConnect(RPostgres::Postgres(), host = "localhost", | |
dbname = "test123", user = "postgres") | |
st_write(pts, pg, "sf_meuse__", overwrite = TRUE) | |
``` | |
Write SQL directly in the Rmarkdown document in a `SQL` chunk | |
(with synatx highlighting): | |
```{sql connection=pg} | |
SELECT | |
landuse, | |
cadmium, | |
ST_X(ST_Transform(geometry, 4326)) longitude, | |
ST_Y(ST_Transform(geometry, 4326)) latitude | |
FROM | |
sf_meuse__; | |
``` | |
Create a table in the database: | |
```{sql connection=pg} | |
DROP TABLE IF EXISTS tmp; | |
``` | |
```{sql connection=pg} | |
CREATE TABLE tmp AS | |
SELECT | |
landuse, | |
cadmium, | |
ST_Buffer(geometry, 100) geometry | |
FROM | |
sf_meuse__; | |
``` | |
Use R to read the table from the database and plot | |
```{r message=FALSE, warning=FALSE} | |
st_read(pg, "tmp") %>% | |
mapview() | |
``` | |
Or write your query directly in the `query` parameter of `st_read`: | |
```{r} | |
st_read(pg, | |
query = "SELECT landuse, cadmium, st_buffer(geometry, 100) geometry | |
FROM sf_meuse__;") | |
``` | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment