<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/data-table-by-example-part-3/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://mathewanalytics.com/2017/09/30/data-table-by-example-part-3/"> R – Mathew Analytics</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>For this final post, I will cover some advanced topics and discuss how to use data tables within user generated functions. Once again, let’s use the Chicago crime data.</p>
<pre>
dat = fread(&quot;rows.csv&quot;)
names(dat) &lt;- gsub(&quot; &quot;, &quot;_&quot;, names(dat))
dat[, c(&quot;value1&quot;, &quot;value2&quot;, &quot;value3&quot;) := sample(1:50, nrow(dat), replace=TRUE)]
dat[1:3]
</pre>
<p>Let’s start by subseting the data. The following code takes the first 50000 rows within the dat dataset, selects four columns, creates three new columns pertaining to the data, and then removes the original date column. The output was saved as to new variable and the user can see the first few columns of the new data table using brackets or head function.</p>
<pre>
ddat = dat[1:50000, .(Date, value1, value2, value3)][, 
               c(&quot;year&quot;, &quot;month&quot;, &quot;day&quot;) := 
                        .(year(mdy_hms(Date)), 
                          month(mdy_hms(Date)),
                          day(mdy_hms(Date)))][,-c(&quot;Date&quot;)]

ddat[1:3]  # same as head(ddat, 3)
</pre>
<p>We can now do some intermediate calculations and suppress their output by using braces.</p>
<pre>
unique(ddat$month)
ddat[, { avg_val1 = mean(value1)
         new_val1 = mean(abs(value2-avg_val1))
         new_val2 = new_val1^2 }, by=month][order(month)]
</pre>
<p>In this simple sample case, we have taken the mean value1 for each month, subtracted it from value2, and then squared that result. The output show the final calculation in the brackets, which is the result from squaring. Note that I also ordered the results by month with the chaining process.</p>
<p>That’s all very nice and convenient, but what if we want to create user defined functions that essentially automate these tasks for future work. Let us start with a function for extracting each component from the date column.</p>
<pre>
ddat = dat[1:50000, .(Date, value1, value2, value3)]

add_engineered_dates &lt;- function(mydt, date_col=&quot;Date&quot;){
   
   new_dt = copy(mydt)
   
   new_dt[, paste0(date_col, &quot;_year&quot;) := year(mdy_hms(get(date_col)))]
   new_dt[, paste0(date_col, &quot;_month&quot;) := month(mdy_hms(get(date_col)))]
   new_dt[, paste0(date_col, &quot;_day&quot;) := day(mdy_hms(get(date_col)))] 
   
   new_dt[, c(date_col) := NULL]
   
   new_dt[]
}
</pre>
<p>We’ve created a new functions that takes two arguments, the data table variable name and the name of the column containing the date values. The first step is to copy the data table so that we are not directly making changes to the original data. Because the goal is to add three new columns that extract the year, month, and day, from the date column, we’ve used the lubridate package to define the date column and then extract the desired values. Furthermore, each new column has been labeled so that it distinctly represents the original date column name and the component that it contains. The final step was to remove the original date column, so we’ve set the date column to NULL. The final line prints the results back to the screen. You can recognize from the code above that the get function is used to take a variable name that represents column names and extract those columns within the function.</p>
<pre>
result = add_engineered_dates(ddat)
result
</pre>
<p><a rel="nofollow" href="https://mathewanalytics.files.wordpress.com/2017/09/screen-shot-2017-09-30-at-12-33-18-pm.png" target="_blank"><img data-orig-file="https://mathewanalytics.files.wordpress.com/2017/09/screen-shot-2017-09-30-at-12-33-18-pm.png" data-orig-size="862,432" data-medium-file="https://mathewanalytics.files.wordpress.com/2017/09/screen-shot-2017-09-30-at-12-33-18-pm.png?w=300&amp;h=150&amp;fit=300%2C150&amp;resize=300%2C150" data-attachment-id="855" data-image-meta="{" data-image-description="" src="https://mathewanalytics.files.wordpress.com/2017/09/screen-shot-2017-09-30-at-12-33-18-pm.png?w=300&h=150&fit=300%2C150&resize=300%2C150" data-permalink="https://mathewanalytics.com/2017/09/30/data-table-by-example-part-3/screen-shot-2017-09-30-at-12-33-18-pm/#main" data-large-file="https://mathewanalytics.files.wordpress.com/2017/09/screen-shot-2017-09-30-at-12-33-18-pm.png?w=862" alt="" data-image-title="Screen Shot 2017-09-30 at 12.33.18 PM" sizes="(max-width: 300px) 100vw, 300px" data-comments-opened="0" class="wp-image-855" data-recalc-dims="1"></a></p>
<p>Let’s now apply the previous code with braces to find the squared difference between value2 and the mean value1 metric.</p>
<pre>
result[, { avg_val1 = mean(value1)
           new_val1 = mean(abs(value2-avg_val1))
           new_val2 = new_val1^2 }, by=.(Date_year,Date_month)][
                  order(Date_year,Date_month)][1:12]
</pre>
<p><a rel="nofollow" href="https://mathewanalytics.files.wordpress.com/2017/09/screen-shot-2017-09-30-at-12-33-00-pm.png" target="_blank"><img data-orig-file="https://mathewanalytics.files.wordpress.com/2017/09/screen-shot-2017-09-30-at-12-33-00-pm.png" data-orig-size="552,442" data-medium-file="https://mathewanalytics.files.wordpress.com/2017/09/screen-shot-2017-09-30-at-12-33-00-pm.png?w=300&amp;h=240&amp;fit=300%2C240&amp;resize=300%2C240" data-attachment-id="856" data-image-meta="{" data-image-description="" src="https://mathewanalytics.files.wordpress.com/2017/09/screen-shot-2017-09-30-at-12-33-00-pm.png?w=300&h=240&fit=300%2C240&resize=300%2C240" data-permalink="https://mathewanalytics.com/2017/09/30/data-table-by-example-part-3/screen-shot-2017-09-30-at-12-33-00-pm/#main" data-large-file="https://mathewanalytics.files.wordpress.com/2017/09/screen-shot-2017-09-30-at-12-33-00-pm.png?w=552" alt="" data-image-title="Screen Shot 2017-09-30 at 12.33.00 PM" sizes="(max-width: 300px) 100vw, 300px" data-comments-opened="0" class="wp-image-856" data-recalc-dims="1"></a></p>
<p>Perfect!</p>
<p>I’m hoping that these three posts on the data.table package have convinced beginners to R of its beauty. The syntax may be scary at first, but this is in my opinion one of the most important packages in R that everyone should become familiar with. So pull your sleeves up and have fun.</p>
<p>If you have any comments or would like to cover other specific topics, feel free to comment below. You can also contact me at mathewanalytics@gmail.com or reach me through LinkedIn</p>
<p> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/mathewanalytics.wordpress.com/854/" target="_blank"><img border="0" alt="" src="http://feeds.wordpress.com/1.0/comments/mathewanalytics.wordpress.com/854/"></a> <img border="0" alt="" src="https://i1.wp.com/pixel.wp.com/b.gif?resize=1%2C1&ssl=1" data-recalc-dims="1"></p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://mathewanalytics.com/2017/09/30/data-table-by-example-part-3/"> R – Mathew Analytics</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 rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/PMoagOreVok" height="1"></a></div>