<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/db-connected-r-application-on-open-source-shiny-server-part-1/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://levashov.biz/db-connected-r-application-on-open-source-shiny-server-part-1/"> R – Alex Levashov – eCommerce Consultant (Melbourne, Australia)</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><img sizes="(max-width: 998px) 100vw, 998px" src="https://i2.wp.com/levashov.biz/wp-content/uploads/2018/12/aupol-shiny.png?w=450&ssl=1" alt="Shiny App" class="wp-image-831" data-wp-pid="831" data-recalc-dims="1"></p>
<p>As a follow-up of my previous <a rel="nofollow" href="https://levashov.biz/scraping-data-about-australian-politicians-with-rselenium/" target="_blank">study</a> of Australian politicians on Twitter I’ve decided to build a more sophisticated, autonomous solution.</p>
<p>The idea at glance:</p>
<ul>
<li>Collect <strong>regularly</strong> tweets from Members of Australian Parliament</li>
<li>Store them in the database</li>
<li>Visualize findings (in up-to-date state) in web dashboard</li>
</ul>
<p>A goal here is to build a solution that once created will work fully autonomously, without need for me to run any single update script manually and present the insights to people who don’t have R for various reasons. It is quite common situation in business when analysts need to build a dashboard that then used by non-technical users.</p>
<h2>Architecture</h2>
<h3>Data collection</h3>
<p>For data collection I’ve decided to use R as a language. It was tempting to play with something like Lambda functions that AWS offers, but there is no R support yet and my Python skills are too basic and I would spend too much time to build something working. The challenge with R is to make it running: (a) on server rather than desktop and (b) have scheduled tasks for regular data collection.</p>
<p>Running R on server isn’t something very novel, there are number of solutions available. I’ve decided to go with the <a rel="nofollow" href="https://www.louisaslett.com/RStudio_AMI/" target="_blank">bundle server solution</a> created Louis Aslett. It includes R, open-source versions of RStudio and Shiny (which I’ll use for visualization part).</p>
<p>Running R script on schedule is possible thanks to <a rel="nofollow" href="https://github.com/bnosac/cronR" target="_blank">CronR</a> package (also available through CRAN).</p>
<h3>Data storage</h3>
<p>For data storage I selected popular relational database MySQL (at AWS RDS). It isn’t very sexy, but the data I am collecting isn’t huge at the moment (a bit over 20,000 records) and nearby future, so more complex solution will be probably an overkill. I also use some DB functionality to process data before it goes back to application: avoid data duplication and merge 2 data tables.</p>
<h3>Visualization</h3>
<p>For visualization I employ Shiny Open Source server. It is part of the package referred above and works just fine for my purpose.</p>
<p>A high level diagram of the solution is presented below.</p>
<div type="\&quot;device\&quot;" data-mxgraph="{">&quot;}&quot;></div>
<p></p>
<p>Let’s now talk about some details.</p>
<h2>RStudio and Shiny server setup</h2>
<p>As was mentioned I am using <a rel="nofollow" href="https://www.louisaslett.com/RStudio_AMI/" target="_blank">an image</a> (AMI) prepared by Louis Aslett. The image is build to easy and quickly deploy the whole server to Amazon Web Services infrastructure. It takes literally 15-20 minutes to do initial deployment and pretty straight forward in general, you need just follow the instructions.</p>
<p>What may take a bit of time is to set it work through secure HTTPS connection.</p>
<p>I’ve managed to achieve it by using self-signed certificate and free account on <a rel="nofollow" href="https://www.cloudflare.com/" target="_blank">Cloudflare</a></p>
<p><strong>Prerequisite: you need to have a domain managed through Cloudflare.</strong></p>
<p>Instructions how to do it.</p>
<p>1. Configure domain or sub-domain pointing to your new EC2 instance. I’ve used CNAME record pointing to Public DNS (IPv4) of my instance. Make sure that you set Full SSL mode in Crypto section of Cloudflare</p>
<p>2. Generate self-signed SSL certificate as per Step One of <a rel="nofollow" href="https://www.digitalocean.com/community/tutorials/how-to-create-an-ssl-certificate-on-nginx-for-ubuntu-14-04" target="_blank">this instruction</a> provided by Digital Ocean. Note that you don’t need to install Nginx, it is already installed.</p>
<p>3. Find Nginx configuration file, specifically with this AMI it is /etc/nginx/sites-available/RStudioAMI.conf</p>
<p>Add there the next lines under Server section:</p>
<p><code># Add SSL support<br>
listen 443 ssl default_server;<br>
listen [::]:443 ssl default_server;<br>
ssl_certificate /etc/nginx/ssl/nginx.crt;<br>
ssl_certificate_key /etc/nginx/ssl/nginx.key;<br>
server_name yourdomain.com</code></p>
<p>Don’t forget to replace <code>yourdomain.com</code> with your actual domain</p>
<p>4. Restart Nginx with sudo service nginx restart</p>
<p>If you did all correctly you now should have your Rstudio available under your domain and Shiny running under yourdomain.com/shiny/rstudio</p>
<h2>Database configuration</h2>
<p>I will not write a tutorial of setting up RDS instance with MySQL, there are tons of them available and in fact you don’t have to use AWS. What is important that at the end of the process you should be able to connect to your database from remote server or desktop through 3306 port.</p>
<p>For security you may keep it open only for whitelisted IPs (like your home computer and R server you created).</p>
<p>There are several things that I deliberately decided to do on database level.</p>
<h3>Initial data collection</h3>
<p>I set some groundwork of collecting tweets from Australian MPs before, so already have list of Members of Parliaments Twitter accounts grouped by parties and a script that collects the tweets.<br>
You may find my script that does initial data collection on <a rel="nofollow" href="https://github.com/alevashov/aupolitics/blob/master/dbcollection-rtweet.R" target="_blank">Github</a>. This script uses <a rel="nofollow" href="https://cran.r-project.org/web/packages/rtweet/index.html" target="_blank">rtweet</a> package to get data from Twitter and <a rel="nofollow" href="https://cran.r-project.org/web/packages/RMySQL/" target="_blank">RMySQL</a> package to work with MySQL database.</p>
<p>Key commands to work with databases from R:<br>
Setup db connection<br>
<code>con &lt;- dbConnect(RMySQL::MySQL(), dbname= db_name, username=user, password=pw, host=host, port=3306)</code><br>
Save data in DB from data frame:<br>
<code>dbWriteTable(con, &quot;tweets2&quot;, t, row.names=FALSE, append=TRUE)</code><br>
Close DB connection:<br>
<code>dbDisconnect(con)</code></p>
<p>What is also important to mention is that data frame has to be flatten before stored to the database, hence flatten <code>function </code>from rtweet package is applied. At the end of this process initial data about tweets and users will be stored in 2 database tables.</p>
<h3>Keep the data of tweets and users unique</h3>
<p>Each tweet and Twitter user has unique id. For data integrity we don’t want to collect duplicate records of users and tweets. It is possible to handle that on application level (in R code), but because the plan is doing regular updates to make R code simpler and quicker (do not upload all database for integrity check) I decided to set the database such a way that that the records be kept unique on database level.</p>
<p>So I set the fields user_id and status_id in corresponding tables as unique. In SQL it looks like:</p>
<p><code>  `user_id` varchar(50) NOT NULL,<br>
PRIMARY KEY (`user_id`),<br>
UNIQUE KEY `user_id_UNIQUE` (`user_id`)</code></p>
<p>Don’t copy-paste this code, because it misses all the other fields in the table. If you don’t know SQL you can easily set that configuration through tool like MySQL Workbench. Similar approach used with status_id in table with tweets.</p>
<h3>Joining users and tweets.</h3>
<p>To make more sense of data, like link tweets with political party we need to join the data of tweets and users. Previously I did that in R code, which is comparatively easy with dplyr. However why not make the DB do this job? Hence I have created a view in MySQL that joins tweets and users table based the next SQL code:</p>
<p><code>    SELECT<br>
twitterr.tweets2.*,<br>
twitterr.users2.party AS 'party'<br>
FROM<br>
(twitterr.tweets2<br>
LEFT JOIN twitterr.users2 ON ((twitterr.tweets2.user_id = twitterr.users2.user_id)))</code><br>
As a result, MySQL on fly creates a view that later can be requested the save way with a table, which is pretty handy – you can load a joined data straight to your data frame for further analysis and visualization.</p>
<p>If you need part of data you can construct a custom SQL query and get for example only last week data set or only a data set covering one party.</p>
<p>That is it for now, stay tuned.</p>
<p>If you can’t wait  – all R code is available at my <a rel="nofollow" href="https://github.com/alevashov/aupolitics/" target="_blank">Github repository</a>.</p>
<p>The Shiny application can be checked here: <a rel="nofollow" href="https://rserv.levashov.biz/shiny/rstudio/" target="_blank">https://rserv.levashov.biz/shiny/rstudio/</a></p>
<p><a rel="nofollow" href="https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Flevashov.biz%2Fdb-connected-r-application-on-open-source-shiny-server-part-1%2F&linkname=DB%20connected%20R%20application%20on%20open-source%20Shiny%20server%2C%20part%201" title="Facebook" target="_blank"></a><a rel="nofollow" href="https://www.addtoany.com/add_to/twitter?linkurl=https%3A%2F%2Flevashov.biz%2Fdb-connected-r-application-on-open-source-shiny-server-part-1%2F&linkname=DB%20connected%20R%20application%20on%20open-source%20Shiny%20server%2C%20part%201" title="Twitter" target="_blank"></a><a rel="nofollow" href="https://www.addtoany.com/add_to/google_plus?linkurl=https%3A%2F%2Flevashov.biz%2Fdb-connected-r-application-on-open-source-shiny-server-part-1%2F&linkname=DB%20connected%20R%20application%20on%20open-source%20Shiny%20server%2C%20part%201" title="Google+" target="_blank"></a><a rel="nofollow" href="https://www.addtoany.com/add_to/linkedin?linkurl=https%3A%2F%2Flevashov.biz%2Fdb-connected-r-application-on-open-source-shiny-server-part-1%2F&linkname=DB%20connected%20R%20application%20on%20open-source%20Shiny%20server%2C%20part%201" title="LinkedIn" target="_blank"></a><a rel="nofollow" href="https://www.addtoany.com/add_to/reddit?linkurl=https%3A%2F%2Flevashov.biz%2Fdb-connected-r-application-on-open-source-shiny-server-part-1%2F&linkname=DB%20connected%20R%20application%20on%20open-source%20Shiny%20server%2C%20part%201" title="Reddit" target="_blank"></a><a data-a2a-title="DB connected R application on open-source Shiny server, part 1" rel="nofollow" href="https://www.addtoany.com/share#url=https%3A%2F%2Flevashov.biz%2Fdb-connected-r-application-on-open-source-shiny-server-part-1%2F&amp;%23038;title=DB%20connected%20R%20application%20on%20open-source%20Shiny%20server%2C%20part%201" data-a2a-url="https://levashov.biz/db-connected-r-application-on-open-source-shiny-server-part-1/" target="_blank"></a></p>
<p>The post <a rel="nofollow" href="https://levashov.biz/db-connected-r-application-on-open-source-shiny-server-part-1/" target="_blank">DB connected R application on open-source Shiny server, part 1</a> appeared first on <a rel="nofollow" href="https://levashov.biz/" target="_blank">Alex Levashov – eCommerce Consultant (Melbourne, Australia)</a>.</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://levashov.biz/db-connected-r-application-on-open-source-shiny-server-part-1/"> R – Alex Levashov – eCommerce Consultant (Melbourne, Australia)</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/qrT0dmVft0E" height="1"></a></div>