SlideShare une entreprise Scribd logo
1  sur  14
Télécharger pour lire hors ligne
Database Access through R

       Krishna Bhogaonker




       December 14, 2010
Where is this Going?

 ●
     Introduction to database connection methods
 ●
     Examples from some common R packages (cheat sheets
     a.k.a. eye charts)
 ●
     Introduction to the sqldf package




14/12/10                Database Access Through R         2
Database access is about fitting round pegs into
square holes.




14/12/10           Database Access Through R       3
Issues to Consider when Choosing a Data
Access Method for Basic Analysis
●
    How much work does it take to set up?
     ●
           Lazy ways – GUIs like RCommander, Deducer, JGR,
           Revolutions, RedR . . . .
     ●
           Diligent ways – Database or Protocol Specific R
           Packages.
●
    Speed
●
    Stability
●
    Platform


14/12/10                    Database Access Through R        4
High-Level Database Connection Procedure

 ●
     Open a database connection object using the
     appropriate driver (ODBC, JDBC, etc.)
 ●
     Authenicate user and confirm connection
 ●
     Execute database tasks by referencing the appropriate
     methods on the database object




14/12/10                Database Access Through R            5
DBI Package

 ●
     Big package with connections to various database
     protocols including Oracle, PostgreSQL, ODBC, SQLite,
     MySQL
     ## choose the proper DBMS driver and connect to the server

           drv <- dbDriver("ODBC")
           con <- dbConnect(drv, "dsn", "usr", "pwd")
     ## the interface can work at a higher level importing tables as data.frames and exporting
     data.frames as DBMS tables.

           dbListTables(con)
           dbListFields(con, "quakes")
           if(dbExistsTable(con, "new_results"))
           dbRemoveTable(con, "new_results")

           dbWriteTable(con, "new_results", new.output)




14/12/10                                 Database Access Through R                               6
RODBC

 ●
     Provides access to ODBC compliant databases,
     including MSSQL, MS Access, and others
     #   connect to database

           library(RODBC)
           myconn <-odbcConnect("mydsn", uid="Rob", pwd="aardvark")
     #   query data from the database

           crimedat <- sqlFetch(myconn, Crime)
           pundat <- sqlQuery(myconn, "select * from Punishment")
     #   close database connection

           close(myconn)




14/12/10                                Database Access Through R     7
RJDBC

 ●
     Uses the DBI interface for the front-end and JDBC
     driver on the back-end
     #   connect to the database

           drv <- JDBC("com.mysql.jdbc.Driver",
               "/etc/jdbc/mysql-connector-java-3.1.14-bin.jar", "`")
           conn <- dbConnect(drv, "jdbc:mysql://localhost/test")
     #   access database tables

           dbListTables(conn)
           data(iris)
     #   write to and query tables

           dbWriteTable(conn, "iris", iris)
           dbGetQuery(conn, "select count(*) from iris")
           d <- dbReadTable(conn, "iris")




14/12/10                               Database Access Through R       8
RMySQL

 ●
     Database interface for MySQL driver using the DBI
     standard.
     ##    connect and authenticate to a MySQL Db

           con <- dbConnect(MySQL(), group = "lasers")
           con2 <- dbConnect(MySQL(), user="opto", password="pure-light",
                dbname="lasers", host="merced"
     ##    list tables ad fields in a table

           dbListTables(con)
           dbListFields(con, "table_name")
     ##    import and export data frames

           d <- dbReadTable(con, "WL")
           dbWriteTable(con, "WL2", a.data.frame)       ## table from a data.frame
           dbWriteTable(con, "test2", "~/data/test2.csv")       ## table from file




14/12/10                                   Database Access Through R                 9
RpgSQL

 ●
     PostgreSQL interface to R via RJDBC
     # the user/password/dbname used here are actually the defaults

           con <- dbConnect(pgSQL(), user = "postgres", password = "", dbname = "test")
     # create table, populate it and display it

           s <- 'create table tt("id" int primary key, "name" varchar(255))'
           dbSendUpdate(con, s)
           dbSendUpdate(con, "insert into tt values(1, 'Hello')")
           dbSendUpdate(con, "insert into tt values(2, 'World')")
           dbGetQuery(con, "select * from tt")
     # transfer a data frame to pgSQL and then display it from the database

     # dbWriteTable is case sensitive

           dbWriteTable(con, "BOD", BOD)
     # table names are lower cased unless double quoted

           dbGetQuery(con, 'select * from "BOD"')



14/12/10                                Database Access Through R                         10
RMongo

 ●
     Access to Mongodb through R. Modeled on RMySQL.
     Still in alpha as of Nov 3, 2010.
     #   connect to a database

           mongo <- mongoDbConnect("eat2treat_development")
     #   show the collections

           dbShowCollections(mongo)
     #   perform an 'all' query with a document limit of 2 and offset of 0.

     # the results is a data.frame object. Nested documents are not supported at the moment. They
     will just be the string output.

           results <- dbGetQuery(mongo, "nutrient_metadatas", "{}", 0, 2)
           names(results)
           results <- dbGetQuery(mongo, "nutrient_metadatas", '{"nutrient_definition_id": 307}')




14/12/10                               Database Access Through R                                    11
A Few Words about the sqldf Package

 ●
     Sqldf provides a way to run SQL statements on R
     dataframes.
 ●
     Sqldf works with the SQLite, H2, and PostgreSQL
     databases.
 ●
     This package allows you to run most SQL commands
     against an R dataframe: Selects, Joins, Ordering,
     Grouping, Averaging, etc.




14/12/10               Database Access Through R         12
Sqldf Example

    # load sqldf into workspace and execute SELECT queries
           library(sqldf)
           sqldf("select * from iris limit 5")
           sqldf("select count(*) from iris")
           sqldf("select Species, count(*) from iris group by
           Species")
    # example of a JOIN
    Abbr <- data.frame(Species = levels(iris$Species),
    +       Abbr = c("S", "Ve", "Vi"))
    sqldf("select Abbr, avg(Sepal_Length)
    +      from iris natural join Abbr group by Species")



14/12/10                     Database Access Through R          13
Thank You




 “How are you going to run the universe if you can't
 answer a few unsolvable problems?”

14/12/10             Database Access Through R         14

Contenu connexe

Tendances

Tendances (20)

Postgre sql unleashed
Postgre sql unleashedPostgre sql unleashed
Postgre sql unleashed
 
BITS: Introduction to relational databases and MySQL - SQL
BITS: Introduction to relational databases and MySQL - SQLBITS: Introduction to relational databases and MySQL - SQL
BITS: Introduction to relational databases and MySQL - SQL
 
MySQL database replication
MySQL database replicationMySQL database replication
MySQL database replication
 
Use Your MySQL Knowledge to Become a MongoDB Guru
Use Your MySQL Knowledge to Become a MongoDB GuruUse Your MySQL Knowledge to Become a MongoDB Guru
Use Your MySQL Knowledge to Become a MongoDB Guru
 
MongoDB Database Replication
MongoDB Database ReplicationMongoDB Database Replication
MongoDB Database Replication
 
Postgresql Database Administration Basic - Day2
Postgresql  Database Administration Basic  - Day2Postgresql  Database Administration Basic  - Day2
Postgresql Database Administration Basic - Day2
 
Json within a relational database
Json within a relational databaseJson within a relational database
Json within a relational database
 
Postgresql Federation
Postgresql FederationPostgresql Federation
Postgresql Federation
 
Perl Programming - 04 Programming Database
Perl Programming - 04 Programming DatabasePerl Programming - 04 Programming Database
Perl Programming - 04 Programming Database
 
Indexing
IndexingIndexing
Indexing
 
Writing A Foreign Data Wrapper
Writing A Foreign Data WrapperWriting A Foreign Data Wrapper
Writing A Foreign Data Wrapper
 
Mysql database basic user guide
Mysql database basic user guideMysql database basic user guide
Mysql database basic user guide
 
My sql tutorial-oscon-2012
My sql tutorial-oscon-2012My sql tutorial-oscon-2012
My sql tutorial-oscon-2012
 
data loading and unloading in IBM Netezza by www.etraining.guru
data loading and unloading in IBM Netezza by www.etraining.gurudata loading and unloading in IBM Netezza by www.etraining.guru
data loading and unloading in IBM Netezza by www.etraining.guru
 
This upload requires better support for ODP format
This upload requires better support for ODP formatThis upload requires better support for ODP format
This upload requires better support for ODP format
 
Building node.js applications with Database Jones
Building node.js applications with Database JonesBuilding node.js applications with Database Jones
Building node.js applications with Database Jones
 
Gur1009
Gur1009Gur1009
Gur1009
 
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
Benefits of Using MongoDB Over RDBMS (At An Evening with MongoDB Minneapolis ...
 
Developing for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQLDeveloping for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQL
 
PHP - Intriduction to MySQL And PHP
PHP - Intriduction to MySQL And PHPPHP - Intriduction to MySQL And PHP
PHP - Intriduction to MySQL And PHP
 

En vedette

Los Angeles R users group - Nov 17 2010 - Part 2
Los Angeles R users group - Nov 17 2010 - Part 2Los Angeles R users group - Nov 17 2010 - Part 2
Los Angeles R users group - Nov 17 2010 - Part 2
rusersla
 
R Journal 2009 1
R Journal 2009 1R Journal 2009 1
R Journal 2009 1
Ajay Ohri
 

En vedette (9)

Los Angeles R users group - Nov 17 2010 - Part 2
Los Angeles R users group - Nov 17 2010 - Part 2Los Angeles R users group - Nov 17 2010 - Part 2
Los Angeles R users group - Nov 17 2010 - Part 2
 
R Journal 2009 1
R Journal 2009 1R Journal 2009 1
R Journal 2009 1
 
Accessing Databases from R
Accessing Databases from RAccessing Databases from R
Accessing Databases from R
 
Merge Multiple CSV in single data frame using R
Merge Multiple CSV in single data frame using RMerge Multiple CSV in single data frame using R
Merge Multiple CSV in single data frame using R
 
R Programming: Importing Data In R
R Programming: Importing Data In RR Programming: Importing Data In R
R Programming: Importing Data In R
 
National seminar on emergence of internet of things (io t) trends and challe...
National seminar on emergence of internet of things (io t)  trends and challe...National seminar on emergence of internet of things (io t)  trends and challe...
National seminar on emergence of internet of things (io t) trends and challe...
 
R Markdown Tutorial For Beginners
R Markdown Tutorial For BeginnersR Markdown Tutorial For Beginners
R Markdown Tutorial For Beginners
 
Tools and techniques for data science
Tools and techniques for data scienceTools and techniques for data science
Tools and techniques for data science
 
RMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRMySQL Tutorial For Beginners
RMySQL Tutorial For Beginners
 

Similaire à Los Angeles R users group - Dec 14 2010 - Part 2

Nko workshop - node js & nosql
Nko workshop - node js & nosqlNko workshop - node js & nosql
Nko workshop - node js & nosql
Simon Su
 

Similaire à Los Angeles R users group - Dec 14 2010 - Part 2 (20)

Jdbc
JdbcJdbc
Jdbc
 
ROracle
ROracle ROracle
ROracle
 
Lecture17
Lecture17Lecture17
Lecture17
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
MongoDB - A next-generation database that lets you create applications never ...
MongoDB - A next-generation database that lets you create applications never ...MongoDB - A next-generation database that lets you create applications never ...
MongoDB - A next-generation database that lets you create applications never ...
 
JDBC (2).ppt
JDBC (2).pptJDBC (2).ppt
JDBC (2).ppt
 
2015 02-09 - NoSQL Vorlesung Mosbach
2015 02-09 - NoSQL Vorlesung Mosbach2015 02-09 - NoSQL Vorlesung Mosbach
2015 02-09 - NoSQL Vorlesung Mosbach
 
Nko workshop - node js & nosql
Nko workshop - node js & nosqlNko workshop - node js & nosql
Nko workshop - node js & nosql
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
Vitalii Bondarenko HDinsight: spark. advanced in memory big-data analytics wi...
 
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
SE2016 BigData Vitalii Bondarenko "HD insight spark. Advanced in-memory Big D...
 
Example R usage for oracle DBA UKOUG 2013
Example R usage for oracle DBA UKOUG 2013Example R usage for oracle DBA UKOUG 2013
Example R usage for oracle DBA UKOUG 2013
 
Jdbc
JdbcJdbc
Jdbc
 
JDBC
JDBCJDBC
JDBC
 
34 using mysql with java
34 using mysql with java34 using mysql with java
34 using mysql with java
 
Module 5 jdbc.ppt
Module 5   jdbc.pptModule 5   jdbc.ppt
Module 5 jdbc.ppt
 
Plmce2015 java 101 - david bennett
Plmce2015   java 101 - david bennettPlmce2015   java 101 - david bennett
Plmce2015 java 101 - david bennett
 
Import Database Data using RODBC in R Studio
Import Database Data using RODBC in R StudioImport Database Data using RODBC in R Studio
Import Database Data using RODBC in R Studio
 
The Ring programming language version 1.8 book - Part 33 of 202
The Ring programming language version 1.8 book - Part 33 of 202The Ring programming language version 1.8 book - Part 33 of 202
The Ring programming language version 1.8 book - Part 33 of 202
 

Plus de rusersla

LA R meetup - Nov 2013 - Eric Klusman
LA R meetup - Nov 2013 - Eric KlusmanLA R meetup - Nov 2013 - Eric Klusman
LA R meetup - Nov 2013 - Eric Klusman
rusersla
 
useR2011 - Whitcher
useR2011 - WhitcheruseR2011 - Whitcher
useR2011 - Whitcher
rusersla
 
useR2011 - Rougier
useR2011 - RougieruseR2011 - Rougier
useR2011 - Rougier
rusersla
 
useR2011 - Huber
useR2011 - HuberuseR2011 - Huber
useR2011 - Huber
rusersla
 
useR2011 - Gromping
useR2011 - Gromping useR2011 - Gromping
useR2011 - Gromping
rusersla
 
useR2011 - Edlefsen
useR2011 - EdlefsenuseR2011 - Edlefsen
useR2011 - Edlefsen
rusersla
 
Los Angeles R users group - July 12 2011 - Part 1
Los Angeles R users group - July 12 2011 - Part 1Los Angeles R users group - July 12 2011 - Part 1
Los Angeles R users group - July 12 2011 - Part 1
rusersla
 
Los Angeles R users group - July 12 2011 - Part 2
Los Angeles R users group - July 12 2011 - Part 2Los Angeles R users group - July 12 2011 - Part 2
Los Angeles R users group - July 12 2011 - Part 2
rusersla
 
Los Angeles R users group - Dec 14 2010 - Part 1
Los Angeles R users group - Dec 14 2010 - Part 1Los Angeles R users group - Dec 14 2010 - Part 1
Los Angeles R users group - Dec 14 2010 - Part 1
rusersla
 
Los Angeles R users group - Dec 14 2010 - Part 3
Los Angeles R users group - Dec 14 2010 - Part 3Los Angeles R users group - Dec 14 2010 - Part 3
Los Angeles R users group - Dec 14 2010 - Part 3
rusersla
 

Plus de rusersla (10)

LA R meetup - Nov 2013 - Eric Klusman
LA R meetup - Nov 2013 - Eric KlusmanLA R meetup - Nov 2013 - Eric Klusman
LA R meetup - Nov 2013 - Eric Klusman
 
useR2011 - Whitcher
useR2011 - WhitcheruseR2011 - Whitcher
useR2011 - Whitcher
 
useR2011 - Rougier
useR2011 - RougieruseR2011 - Rougier
useR2011 - Rougier
 
useR2011 - Huber
useR2011 - HuberuseR2011 - Huber
useR2011 - Huber
 
useR2011 - Gromping
useR2011 - Gromping useR2011 - Gromping
useR2011 - Gromping
 
useR2011 - Edlefsen
useR2011 - EdlefsenuseR2011 - Edlefsen
useR2011 - Edlefsen
 
Los Angeles R users group - July 12 2011 - Part 1
Los Angeles R users group - July 12 2011 - Part 1Los Angeles R users group - July 12 2011 - Part 1
Los Angeles R users group - July 12 2011 - Part 1
 
Los Angeles R users group - July 12 2011 - Part 2
Los Angeles R users group - July 12 2011 - Part 2Los Angeles R users group - July 12 2011 - Part 2
Los Angeles R users group - July 12 2011 - Part 2
 
Los Angeles R users group - Dec 14 2010 - Part 1
Los Angeles R users group - Dec 14 2010 - Part 1Los Angeles R users group - Dec 14 2010 - Part 1
Los Angeles R users group - Dec 14 2010 - Part 1
 
Los Angeles R users group - Dec 14 2010 - Part 3
Los Angeles R users group - Dec 14 2010 - Part 3Los Angeles R users group - Dec 14 2010 - Part 3
Los Angeles R users group - Dec 14 2010 - Part 3
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Los Angeles R users group - Dec 14 2010 - Part 2

  • 1. Database Access through R Krishna Bhogaonker December 14, 2010
  • 2. Where is this Going? ● Introduction to database connection methods ● Examples from some common R packages (cheat sheets a.k.a. eye charts) ● Introduction to the sqldf package 14/12/10 Database Access Through R 2
  • 3. Database access is about fitting round pegs into square holes. 14/12/10 Database Access Through R 3
  • 4. Issues to Consider when Choosing a Data Access Method for Basic Analysis ● How much work does it take to set up? ● Lazy ways – GUIs like RCommander, Deducer, JGR, Revolutions, RedR . . . . ● Diligent ways – Database or Protocol Specific R Packages. ● Speed ● Stability ● Platform 14/12/10 Database Access Through R 4
  • 5. High-Level Database Connection Procedure ● Open a database connection object using the appropriate driver (ODBC, JDBC, etc.) ● Authenicate user and confirm connection ● Execute database tasks by referencing the appropriate methods on the database object 14/12/10 Database Access Through R 5
  • 6. DBI Package ● Big package with connections to various database protocols including Oracle, PostgreSQL, ODBC, SQLite, MySQL ## choose the proper DBMS driver and connect to the server drv <- dbDriver("ODBC") con <- dbConnect(drv, "dsn", "usr", "pwd") ## the interface can work at a higher level importing tables as data.frames and exporting data.frames as DBMS tables. dbListTables(con) dbListFields(con, "quakes") if(dbExistsTable(con, "new_results")) dbRemoveTable(con, "new_results") dbWriteTable(con, "new_results", new.output) 14/12/10 Database Access Through R 6
  • 7. RODBC ● Provides access to ODBC compliant databases, including MSSQL, MS Access, and others # connect to database library(RODBC) myconn <-odbcConnect("mydsn", uid="Rob", pwd="aardvark") # query data from the database crimedat <- sqlFetch(myconn, Crime) pundat <- sqlQuery(myconn, "select * from Punishment") # close database connection close(myconn) 14/12/10 Database Access Through R 7
  • 8. RJDBC ● Uses the DBI interface for the front-end and JDBC driver on the back-end # connect to the database drv <- JDBC("com.mysql.jdbc.Driver", "/etc/jdbc/mysql-connector-java-3.1.14-bin.jar", "`") conn <- dbConnect(drv, "jdbc:mysql://localhost/test") # access database tables dbListTables(conn) data(iris) # write to and query tables dbWriteTable(conn, "iris", iris) dbGetQuery(conn, "select count(*) from iris") d <- dbReadTable(conn, "iris") 14/12/10 Database Access Through R 8
  • 9. RMySQL ● Database interface for MySQL driver using the DBI standard. ## connect and authenticate to a MySQL Db con <- dbConnect(MySQL(), group = "lasers") con2 <- dbConnect(MySQL(), user="opto", password="pure-light", dbname="lasers", host="merced" ## list tables ad fields in a table dbListTables(con) dbListFields(con, "table_name") ## import and export data frames d <- dbReadTable(con, "WL") dbWriteTable(con, "WL2", a.data.frame) ## table from a data.frame dbWriteTable(con, "test2", "~/data/test2.csv") ## table from file 14/12/10 Database Access Through R 9
  • 10. RpgSQL ● PostgreSQL interface to R via RJDBC # the user/password/dbname used here are actually the defaults con <- dbConnect(pgSQL(), user = "postgres", password = "", dbname = "test") # create table, populate it and display it s <- 'create table tt("id" int primary key, "name" varchar(255))' dbSendUpdate(con, s) dbSendUpdate(con, "insert into tt values(1, 'Hello')") dbSendUpdate(con, "insert into tt values(2, 'World')") dbGetQuery(con, "select * from tt") # transfer a data frame to pgSQL and then display it from the database # dbWriteTable is case sensitive dbWriteTable(con, "BOD", BOD) # table names are lower cased unless double quoted dbGetQuery(con, 'select * from "BOD"') 14/12/10 Database Access Through R 10
  • 11. RMongo ● Access to Mongodb through R. Modeled on RMySQL. Still in alpha as of Nov 3, 2010. # connect to a database mongo <- mongoDbConnect("eat2treat_development") # show the collections dbShowCollections(mongo) # perform an 'all' query with a document limit of 2 and offset of 0. # the results is a data.frame object. Nested documents are not supported at the moment. They will just be the string output. results <- dbGetQuery(mongo, "nutrient_metadatas", "{}", 0, 2) names(results) results <- dbGetQuery(mongo, "nutrient_metadatas", '{"nutrient_definition_id": 307}') 14/12/10 Database Access Through R 11
  • 12. A Few Words about the sqldf Package ● Sqldf provides a way to run SQL statements on R dataframes. ● Sqldf works with the SQLite, H2, and PostgreSQL databases. ● This package allows you to run most SQL commands against an R dataframe: Selects, Joins, Ordering, Grouping, Averaging, etc. 14/12/10 Database Access Through R 12
  • 13. Sqldf Example # load sqldf into workspace and execute SELECT queries library(sqldf) sqldf("select * from iris limit 5") sqldf("select count(*) from iris") sqldf("select Species, count(*) from iris group by Species") # example of a JOIN Abbr <- data.frame(Species = levels(iris$Species), + Abbr = c("S", "Ve", "Vi")) sqldf("select Abbr, avg(Sepal_Length) + from iris natural join Abbr group by Species") 14/12/10 Database Access Through R 13
  • 14. Thank You “How are you going to run the universe if you can't answer a few unsolvable problems?” 14/12/10 Database Access Through R 14