Thursday, July 15, 2010

Using postgres from R

To use postgres from R, you can follow these steps:

1. Install R
http://cran.r-project.org/bin/linux/ubuntu/

2. Install a postgresql client
https://help.ubuntu.com/community/PostgreSQL

3. From R install packages DBI and RPostgreSQL
Download the packages DBI and RPostgreSQL from CRAN.
Then install them:
sudo R CMD INSTALL DBI_0.2-5.tar.gz
sudo R CMD INSTALL RPostgreSQL_0.1-6.tar.gz

Now you should be able to connect to postgresql databases from R.

To do so, you can use this code fragment:

library(DBI)
library(RPostgreSQL)
drv <- dbDriver("PostgreSQL")
con <- dbConnect(drv, dbname="my_database_name",host="my_host_name", user="my_dbuser", password="my_password", port= database_port_number)
tableXX <- dbGetQuery(con, "select * from tableXX")

NOTE: In Linux this process is very straightforward. In Windows you have to make sure your Postgres bin directory is contained within your path variable definition. (http://support.microsoft.com/kb/310519)

0 Comments:

Post a Comment

<< Home