Skip to content

Instantly share code, notes, and snippets.

@reinholdsson
Last active August 29, 2015 14:07
Show Gist options
  • Save reinholdsson/6aa2a88168aee4c7a641 to your computer and use it in GitHub Desktop.
Save reinholdsson/6aa2a88168aee4c7a641 to your computer and use it in GitHub Desktop.
Install PostgreSQL PL/R on Mac OS X

In terminal:

cd ~
curl "http://www.joeconway.com/plr/plr-8.3.0.15.tar.gz" -o "plr-8.3.0.15.tar.gz"
tar xzf plr-8.3.0.15.tar.gz 
cd plr
R_HOME="/Library/Frameworks/R.framework/Resources/" USE_PGXS=1 PG_CONFIG="/Applications/Postgres.app/Contents/Versions/9.3/bin/pg_config" make
R_HOME="/Library/Frameworks/R.framework/Resources/" USE_PGXS=1 PG_CONFIG="/Applications/Postgres.app/Contents/Versions/9.3/bin/pg_config" make install
'/Applications/Postgres.app/Contents/Versions/9.3/bin'/psql -p5432 test

In PostgreSQL (http://www.bostongis.com/PrinterFriendly.aspx?content_name=postgresql_plr_tut01):

CREATE EXTENSION plr;

In R:

install.packages("dplyr")
install.packages("RPostgreSQL")

Installing RPostgreSQL might cause some issues, if so, install gcc from here: https://github.com/kennethreitz/osx-gcc-installer

library(dplyr)
db <- src_postgres(
dbname = 'test',
host = 'localhost',
port = 5432L
)
# Create mtcars table
dbWriteTable(db$con, "mtcars", mtcars)
res <- dbSendQuery(db$con, "SELECT * FROM mtcars WHERE cyl = 4;")
dbFetch(res)
dbClearResult(res)
# Create median2 function
dbSendQuery(db$con, "
create or replace function r_median(_float8)
returns float as 'median(arg1)' language 'plr';
DROP AGGREGATE IF EXISTS median2(float8);
CREATE AGGREGATE median2 (
sfunc = plr_array_accum,
basetype = float8,
stype = _float8,
finalfunc = r_median
);
")
# Try it out
tbl(db, 'mtcars') %>% summarise(median2(disp)) %>% collect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment