Skip to content

Instantly share code, notes, and snippets.

@benizar
Created October 11, 2013 11:20
Show Gist options
  • Save benizar/6933132 to your computer and use it in GitHub Desktop.
Save benizar/6933132 to your computer and use it in GitHub Desktop.
This code creates a pl/R function for creating histograms directly from a PostgreSQL database. Want more info? Visit our www.gisandchips.org blog (http://www.gisandchips.org/2009/09/24/integracion-de-r-en-postgresql-mi-primera-funcion-en-plr/#more-165).
CREATE OR REPLACE FUNCTION _plr_hist(text, text)
RETURNS text AS
$BODY$
select = 'select '
campo = arg1
from = ' from '
tabla = arg2
selection = paste(select, campo, from, tabla, sep='');
## Ejecutamos la consulta y la almacenamos en el objeto "sql";
sql <- pg.spi.exec (selection);
## Lo que obtengamos a partir de aquí se imprimirá en un pdf...
dir='c:/temp/';
nam= arg1;
ext='.png';
newfile=paste(dir,nam,ext, sep='')
png(newfile);
hist(sql[,1], xlab = campo, ylab='frecuencias', main= campo, col='blue', ylim=c(0,20));
## Hasta aquí
dev.off();
## Si trabajamos en linux querremos hacer algo como lo siguiente
## para asignar privilegios de lectura a todos los usuarios de linux
##sys1='chmod go+r'
##sys2=paste(sys1, '', newfile)
##system(sys2)
## Esto devuelve un mensaje al terminar la función
print1='¡¡¡Ya está!!!, ¡¡¡mira que gráfico más chulo en'
print2=paste(print1, '', newfile, sep='')
print (print2);
$BODY$
LANGUAGE 'plr' VOLATILE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment