<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/rdbl-manipulate-data-in-database-with-r-code-only/"></div></div><div><a data-url="https://www.r-bloggers.com/rdbl-manipulate-data-in-database-with-r-code-only/" data-counturl="https://www.r-bloggers.com/rdbl-manipulate-data-in-database-with-r-code-only/" data-count="horizontal" data-text="RDBL – manipulate data in-database with R code only" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://datascienceplus.com/rdbl-manipulate-data-in-database-with-r-code-only/"> DataScience+</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>In this post I introduce our own package RDBL, the R DataBase Layer. With this package you can manipulate data in-database without writing SQL code. The package interprets the R code and sends out the corresponding SQL statements to the database, fully transparently. To minimize overhead, the data is only fetched when absolutely necessary, allowing the user to create the relevant joins (merge), filters (logical indexing) and groupings (aggregation) in R code before the SQL is run on the database. The core idea behind RDBL is to let R users with little or no SQL knowledge to utilize the power of SQL database engines for data manipulation.</p>
<p>It is important to note that the SQL statements generated in the background are not executed unless explicitly requested by the command as.data.frame. Hence, you can merge, filter and aggregate your dataset on the database side and load only the result set into memory for R.</p>
<p>In general the design principle behind RDBL is to keep the models as close as possible to the usual data.frame logic, including (as shown later in detail) commands like aggregate, referencing columns by the \($\) operator and features like logical indexing using the \([]\) operator.</p>
<p>RDBL supports a connection to any SQL-like data source which supports a DBI interface or an ODBC connection, including but not limited to Oracle, MySQL, SQLite, SQL Server, MS Access and more.</p>
<p>To install RDBL, run the following command:</p>
<pre>
install.packages(&quot;RDBL&quot;, 
                 repos = c(&quot;https://lair.functionalfinances.com/repos/cran/&quot;, 
                           &quot;https://lair.functionalfinances.com/repos/shared/&quot;))</pre>
<p>That’s right: you can install our private package (and all its dependencies) with an install.packages command, instead of the usual install_git setup where you have to go hunting for each dependency! For that kind of magic, we use laiR, our private R repository solution. You can find a demo version of this tool at lair.ownr.io. To hear more about that, please leave a comment and I will reach out to you.</p>
<p>For the source code, head to our private git repo and download the project.</p>
<p>Please note: the examples below require either RSQLite or RMySQL installed as well. In general you will need a connection driver package for the database you want to use RDBL with. It can be any database supporting either DBI or ODBC connections, let it be ROracle for your Oracle database or RSQLServer for your SQL Server. From here on, it is assumed that you have RDBL installed and loaded as well as the connection driver for the database you are using and you have set up a connection:</p>
<pre>
# load the package for the database driver
library(RSQLite)
# create a connection to the SQLite database
dbfile &lt;- &quot;Chinook_Sqlite.sqlite&quot;
db.connection &lt;- dbConnect(SQLite(), dbfile) 
SetConnection(db.connection)
</pre>
<p>If you want to use these examples with your own database, make sure to set up the DB connection to the database in place of the example connection to the SQLite database delivered along with the package.</p>
<p>The package comes with a database example in SQLite and one in MySQL. All examples below are using the SQLite database but everything works exactly the same way for the MySQL example database as well. For database layout see this link for the example database. The project you have downloaded also contains an example.R file showing how to use the package – this post walks you through that example.R file to showcase the possibilities.</p>
<h2>Setting up the database models</h2>
<p>RDBL provides an abstract representation for the database tables called a db.model. A db.model defines names for the table and its columns to be used in R. This serves two purposes: first, some databases support naming conventions that R does not (e.g. SQL Server allows spaces in column names) and, secondly and more importantly, this allows a decoupling of the physical data model and the R code, i.e. changes to the table name or the column names do not require changes to the code in any other place then the definition of the db.model.</p>
<pre>
# set up a database model using default settings
artist.db &lt;- db.model(&quot;Artist&quot;)

# set up a database model defining mappings on the fly
artist.db.mapping &lt;- db.model(&quot;Artist&quot;, 
                              ArtistId = &quot;ArtistId&quot;, 
                              Name = &quot;ArtistName&quot;)</pre>
<p>As you can see, you can either use the default mapping for a table, in which case column names from the table are used as R names or you can specify the R names for the columns (but then you have to specify a name for each column you want in the db.model – any column you don't provide a mapping for will be left out of the model). Note that in case of the database containing non-supported characters in the column names you should always create an explicit mapping!</p>
<p>A quick look at the class of these variables show that they are indeed db.model's:</p>
<pre>
class(artist.db)
<em>[1] &quot;db.model&quot;</em>
attr(,&quot;package&quot;)
<em>[1] &quot;RDBL&quot;</em></pre>
<p>To get the column names for a db.model, simply use the names command, just like in case a of data.frame:</p>
<pre>names(artist.db)
<em>[1] &quot;ArtistId&quot; &quot;Name&quot;</em>

names(artist.db.mapping)
<em>[1] &quot;ArtistId&quot; &quot;ArtistName&quot;</em></pre>
<p>As noted earlier, you can reference the columns of a db.model using the $ operator:</p>
<pre>artist.db$Name
<em>[1] &quot;db.column&quot;</em></pre>
<p>To actually load the data for a model, simply convert it to a data.frame:</p>
<pre>
# load in the data from some of the tables
artists &lt;- as.data.frame(artist.db)

artists
<em> ArtistId Name
1 1 AC/DC
2 2 Accept
...
274 274 Nash Ensemble
275 275 Philip Glass Ensemble</em></pre>
<p>Before we continue, let's set up some more models to showcase the possibilities:</p>
<pre>
# set up other database models for future use
album.db &lt;- db.model(&quot;Album&quot;)
track.db &lt;- db.model(&quot;Track&quot;)
genre.db &lt;- db.model(&quot;Genre&quot;)</pre>
<h2>Adding derived columns</h2>
<p>When defining models, another exciting possibility is adding a new column derived from other columns in the table, using simple SQL operators such as the + operator:</p>
<pre>
# define a new column using basic SQL operations such as +
track.db.mapping &lt;- db.model(&quot;Track&quot;,
                             TrackId = &quot;TrackId&quot;,
                             AlbumId = &quot;AlbumId&quot;,
                             Bytes = &quot;Bytes&quot;,
                             GenreId = &quot;GenreId&quot;,
                             &quot;Bytes + Bytes&quot; = &quot;Bytes2&quot;)

head(as.data.frame(track.db.mapping), 3)
<em> TrackId AlbumId Bytes GenreId Bytes2
1 1 1 11170334 1 22340668
2 2 2 5510424 1 11020848
3 3 3 3990994 1 7981988</em></pre>
<p>Any SQL operator valid for a SELECT statement can be used in this form. Of course the new column is only &quot;created&quot; in the db.model, not in the actual database. Note: different databases may support different operators!</p>
<h2>Renaming columns</h2>
<p>One can also rename columns in the db.model, e.g. to make merging simpler:</p>
<pre>
# rename columns with the same name
# Note: no changes made to the database itself!
rename(genre.db, &quot;Name&quot;, &quot;GenreName&quot;)

names(genre.db)
<em>[1] &quot;GenreId&quot; &quot;GenreName&quot;</em></pre>
<p>Alternatively, you can also assign values to the names(db.model) just like in case of a data.frame:</p>
<pre>names(artist.db) &lt;- c(&quot;ArtistId&quot;, &quot;ArtistName&quot;)
names(artist.db)

<em>[1] &quot;ArtistId&quot; &quot;ArtistName&quot;</em></pre>
<p>The same note applies: the renaming does not effect the database.</p>
<h2>Merge is the now join</h2>
<p>Another way to define a db.model is by merging other db.models (effectively creating a join on the database side):</p>
<pre># join tables together using merge
# artist x album x track x genre to get the mapping between artists and genre
artist.genre.db &lt;- 
  merge(merge(merge(artist.db,
                    album.db,
                    by = &quot;ArtistId&quot;)[,c(&quot;ArtistName&quot;, 
                                        &quot;AlbumId&quot;)],
              track.db,
              by = &quot;AlbumId&quot;)[, c(&quot;ArtistName&quot;,
                                  &quot;GenreId&quot;)],
        genre.db,
        by = &quot;GenreId&quot;)[, c(&quot;ArtistName&quot;,
                            &quot;GenreName&quot;)]</pre>
<p>Note: No data was loaded, instead a new db.model is created, see the class of the object:</p>
<pre>class(artist.genre.db)
<em>[1] &quot;db.join&quot;
attr(,&quot;package&quot;)
[1] &quot;RDBL&quot;</em></pre>
<p>it's not a db.model, it's a db.join which is a subclass of db.model.</p>
<p>A closer look at this new model shows that only the columns specified in the /([]/) operators are included:</p>
<pre>names(artist.genre.db)
<em>[1] &quot;ArtistName&quot; &quot;GenreName&quot;</em></pre>
<p>Exactly the same model can be created by merging step-by-step:</p>
<pre># merge artists and albums, then restrict to several columns
artist.album.db &lt;-
  merge(artist.db,
        album.db,
        by = &quot;ArtistId&quot;)[,c(&quot;ArtistName&quot;, 
                            &quot;AlbumId&quot;)]

# merge tracks and genres
track.genre.db &lt;- 
  merge(track.db.mapping,
        genre.db,
        by = &quot;GenreId&quot;)[,c(&quot;AlbumId&quot;, 
                           &quot;GenreName&quot;)]

# merge the previous two merges to get the 
# artist-genre mapping
artist.genre.db.2 &lt;- merge(artist.album.db,
                           track.genre.db)[, c(&quot;ArtistName&quot;,
                                               &quot;GenreName&quot;)]</pre>
<h2>Logical indexing and column restrictions</h2>
<p>Just like a data.frame, a db.model can be filtered by logical indexing and the columns to be returned can be specified as well:</p>
<pre>
# artists who have at least 1 rock song
rock.artists.db &lt;- 
  unique(
    artist.genre.db[artist.genre.db$GenreName == &quot;Rock&quot;, &quot;ArtistName&quot;]
  )

# note: again, no data loaded, see the class of the object
class(rock.artists.db)
<em>[1] &quot;db.unique&quot;</em>
attr(,&quot;package&quot;)
<em>[1] &quot;RDBL&quot;</em></pre>
<p>It is interesting to note that the class is db.unique. Just like in case of db.join, db.unique is also a subclass of db.model.</p>
<h2>Sorting</h2>
<p>Ordering a db.model is also possible:</p>
<pre>
# one can also order the db.models
rock.artists.db.ordered &lt;- rock.artists.db[order.db(rock.artists.db$ArtistName)]</pre>
<p>Now let's load the result set for a quick look:</p>
<pre>rock.artists &lt;- 
  as.data.frame(rock.artists.db.ordered)

head(rock.artists, 4)
<em> ArtistName
1 AC/DC
2 Accept
3 Aerosmith
4 Alanis Morissette</em></pre>
<h2>Aggregating! In-database!</h2>
<p>As you can know from my previous posts, I love aggregating! Fortunately, RDBL supports the aggregate command with a data.table-like syntax:</p>
<pre>
# which group has the most rock songs?
# aggregate on the database side
rocks &lt;- artist.genre.db[artist.genre.db$GenreName == &quot;Rock&quot;, ]  
most.rock.db &lt;-     
  aggregate(rocks, 
            list(SongCount = count(rocks$GenreName)), 
            by = &quot;ArtistName&quot;)

class(most.rock.db)
<em>[1] &quot;db.join&quot;</em>
attr(,&quot;package&quot;)
<em>[1] &quot;RDBL&quot;</em>


# order the dataset by number of rock songs in decreasing order
most.rock.db &lt;- most.rock.db[order.db(most.rock.db$SongCount, 
                                      decreasing = TRUE)]

# load the resulting data set from the database
head(as.data.frame(most.rock.db), 3)
<em> ArtistName SongCount
1 Led Zeppelin 114
2 U2 112
3 Deep Purple 92</em></pre>
<p>You can also aggregate without specifying the by statement (effectively leaving out the GROUP BY statement on the database side):</p>
<pre>
# aggregate without a 'by' - aggregating through the whole (filtered) table
as.data.frame(aggregate(track.db[track.db$GenreId == 2, ], 
                        list(count = count(track.db$Name), 
                             total.size = sum(track.db$Bytes))))  

  count total.size
<em>1 130 1233457751</em></pre>
<p>As you can see you can define the aggregated columns in a list just like in data.table, while the by statement expects a character vector of the column names to group-by by (no pun intended).</p>
<h2>Persisting</h2>
<p>Finally, you can write a data set back to the database by using the default column mapping (in this case it is expected that the columns in the data.frame map one-to-one to the columns in the target db.model) or by specifying the column mapping yourself:</p>
<pre>
# write records into an existing table using auto-mapping of columns
auto.map.df &lt;- data.frame(ArtistId = as.integer(runif(n=1, 
                                                      min = 8000000, 
                                                      max = 80000001)), 
                          ArtistName = &quot;New_Artist&quot;)

write.db(auto.map.df, 
         artist.db, 
         append = TRUE)

# write records into an existing table using user-defined mapping of columns
to.map.df &lt;- data.frame(aid = as.integer(runif(n=1, 
                                               min = 8000000, 
                                               max = 80000001)), 
                        aname = &quot;New_Artist_2&quot;)

write.db(to.map.df, 
         artist.db, 
         append = TRUE,
         mapping = list(ArtistId = &quot;aid&quot;,
                        ArtistName = &quot;aname&quot;))</pre>
<p>That's all, folks! As you can see, RDBL allows database-manipulation from R without knowing SQL, although that never hurts. It also adds an abstraction layer in R to decouple from the physical data model. Finally, and, for many, most importantly: it allows loading resulting data sets only, trusting the database to do the heavy lifting when it comes to JOINs, WHERE clauses and GROUP BY statements (or merges, logical indexing and aggregation) reducing the size of the actually loaded data dramatically.</p>
<ul></ul>
<p><strong>
<p>Related Post</p>
<p>
<ol>
<li><a title="Permanent Link toR Markdown: How to format tables and figures in .docx files" target="_blank" rel="bookmark" href="http://datascienceplus.com/r-markdown-how-to-format-tables-and-figures-in-docx-files/">R Markdown: How to format tables and figures in .docx files</a></li>
<li><a title="Permanent Link toR Markdown: How to insert page breaks in a MS Word document" target="_blank" rel="bookmark" href="http://datascienceplus.com/r-markdown-how-to-insert-page-breaks-in-a-ms-word-document/">R Markdown: How to insert page breaks in a MS Word document</a></li>
<li><a title="Permanent Link toWorking on Data-Warehouse (SQL) with R" target="_blank" rel="bookmark" href="http://datascienceplus.com/working-on-data-warehouse-sql-with-r/">Working on Data-Warehouse (SQL) with R</a></li>
<li><a title="Permanent Link toImplementing Apriori Algorithm in R" target="_blank" rel="bookmark" href="http://datascienceplus.com/implementing-apriori-algorithm-in-r/">Implementing Apriori Algorithm in R</a></li>
<li><a title="Permanent Link toHandling missing data with MICE package; a simple approach" target="_blank" rel="bookmark" href="http://datascienceplus.com/handling-missing-data-with-mice-package-a-simple-approach/">Handling missing data with MICE package; a simple approach</a></li>
</ol></strong>
<div>
<a target="_blank" href="http://feeds.feedburner.com/~ff/datascienceplus?a=b_ZugBt3-Gs:GYbaZEdGzwc:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/datascienceplus?i=b_ZugBt3-Gs:GYbaZEdGzwc:D7DqB2pKExk" border="0"></a> <a target="_blank" href="http://feeds.feedburner.com/~ff/datascienceplus?a=b_ZugBt3-Gs:GYbaZEdGzwc:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/datascienceplus?d=qj6IDK7rITs" border="0"></a> <a target="_blank" href="http://feeds.feedburner.com/~ff/datascienceplus?a=b_ZugBt3-Gs:GYbaZEdGzwc:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/datascienceplus?d=yIl2AUoC8zA" border="0"></a>
</div>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="https://www.r-bloggers.com/rdbl-manipulate-data-in-database-with-r-code-only/"></div></div><div><a data-url="https://www.r-bloggers.com/rdbl-manipulate-data-in-database-with-r-code-only/" data-counturl="https://www.r-bloggers.com/rdbl-manipulate-data-in-database-with-r-code-only/" data-count="vertical" data-text="RDBL – manipulate data in-database with R code only" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://datascienceplus.com/rdbl-manipulate-data-in-database-with-r-code-only/"> DataScience+</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/?s=Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/Wa09I8yq8EQ"></a></div>