<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tim M. Schendzielorz on Medium]]></title>
        <description><![CDATA[Stories by Tim M. Schendzielorz on Medium]]></description>
        <link>https://medium.com/@tschendzie_99009?source=rss-7056b9dfb238------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*ftoPqBYdClPpz8ZYL85lKQ.jpeg</url>
            <title>Stories by Tim M. Schendzielorz on Medium</title>
            <link>https://medium.com/@tschendzie_99009?source=rss-7056b9dfb238------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:42:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tschendzie_99009/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Deploying an R Shiny app on Heroku free tier]]></title>
            <link>https://medium.com/analytics-vidhya/deploying-an-r-shiny-app-on-heroku-free-tier-b31003858b68?source=rss-7056b9dfb238------2</link>
            <guid isPermaLink="false">https://medium.com/p/b31003858b68</guid>
            <category><![CDATA[r]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[shiny]]></category>
            <category><![CDATA[continuous-deployment]]></category>
            <dc:creator><![CDATA[Tim M. Schendzielorz]]></dc:creator>
            <pubDate>Tue, 24 Nov 2020 04:51:15 GMT</pubDate>
            <atom:updated>2022-03-22T08:51:37.197Z</atom:updated>
            <content:encoded><![CDATA[<p>Continuous Deployment made easy with GitHub Actions and Heroku</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*U6ARH-YNN-e6SqJI.png" /></figure><p><em>This article is a short guide on deploying a Shiny app on Heroku. Familiarity with Docker, Shiny and GitHub is presumed. For an introduction to Docker, see </em><a href="https://medium.com/analytics-vidhya/deploying-a-shiny-flexdashboard-with-docker-cca338a10d12"><em>Deploying a Shiny Flexdashboard with Docker</em></a><em>.</em></p><p><em>This article was also published on </em><a href="https://www.r-bloggers.com/"><em>https://www.r-bloggers.com/</em></a><em>.</em></p><h4>This article will show you</h4><ul><li>What Heroku is and what you can get for free</li><li>How to containerize a Shiny app with Docker</li><li>How to set up GitHub to automatically deploy to Heroku</li><li>How to set up a custom domain name for your deployed app</li></ul><h3>Heroku free tier</h3><p><a href="https://www.heroku.com/home">Heroku</a> (which I am not affiliated with) is a cloud platform service that offers an intuitive way to deploy and manage enterprise grade web apps. It enables easy auto scaling of your apps, however not on Free (and Hobby) tier we will use here. Apps can be managed via CLI or the Heroku dashboard.</p><p>Heroku has a plethora of <a href="https://elements.heroku.com/addons">addons</a>, e.g. for logging or messaging. Additionally it provides services you can co-deploy with your apps like databases with just a few clicks or lines in the CLI or in a deploy instruction file, the `heroku.yml`.</p><p>With the new <a href="https://devcenter.heroku.com/articles/build-docker-images-heroku-yml">heroku.ym</a>l file it is possible to deploy multi container apps. Here however we will not use a heroku.yml as the deployment will be managed by GitHub Actions.</p><p>Heroku apps run in “dynos” which are containers running on AWS. With the free tier you can run apps in max 5 dynos (100 if you verify) with 512 MB memory each and get 550 (1000 if you verify) dyno hours. On free tier your apps go to “sleep mode” after 30 min and need to be woken up, which usually means your load time on the first request will be 10–30s longer. This behavior saves your free dyno hours. If you want to circumvent this, add a GET Request to your app so that the app will call itself in intervals &lt; 30 min. We`ll see how long this will be possible.</p><p>What I like about the Heroku pricing model is that it is per app. That means you can upgrade a single app after testing it on free tier. On paid tiers you get various benefits, like auto scaling, unlimited dyno hours and SSL encryption with custom domains.</p><h3>Shiny app Docker image</h3><p>Heroku dynos support a few languages out of the box like Python and GO with provided <a href="https://elements.heroku.com/buildpacks">buildpacks</a>. There are <a href="https://davidquartey.medium.com/how-i-installed-r-on-heroku-ff8286233d2c">unofficial </a>buildpacks for R on <a href="https://github.com/virtualstaticvoid/heroku-buildpack-r">github</a>. However, here we will use a Docker container to run in the dyno. Furthermore putting your Shiny app in a Docker container has various advantages such as properly managing dependencies and good portability across systems.</p><p>In this example an R Shiny app that provides batch geo-coding of addresses to longitude and latitude is deployed. In the repo you can find and clone the Shiny app, Dockerfile and GitHub Actions YAML: <a href="https://github.com/timosch29/geocoding_shiny">https://github.com/timosch29/geocoding_shiny</a></p><p>The deployed app can be reached at <a href="https://geocoding.timschendzielorz.com/">geocoding.timschendzielorz.com</a>.</p><p>For the deployment on Heroku you have to modify the Dockerfile instructions a bit.</p><pre># Base image https://hub.docker.com/u/rocker/                       FROM rocker/shiny-verse:4.0.3</pre><pre>LABEL author=&quot;Tim M.Schendzielorz docker@timschendzielorz.com&quot;</pre><pre># system libraries of general use                       <br># install debian packages                       <br>RUN apt-get update -qq &amp;&amp; apt-get -y --no-install-recommends install \ <br>    libxml2-dev \<br>    libcairo2-dev \<br>    libpq-dev \ <br>    libssh2-1-dev \<br>    libcurl4-openssl-dev \<br>    libssl-dev</pre><pre># update system libraries<br>RUN apt-get update &amp;&amp; \ <br>    apt-get upgrade -y &amp;&amp; \  <br>    apt-get clean</pre><pre># copy necessary files from app folder<br># Shiny app <br>COPY /shiny_geocode ./app                       <br># renv.lock file<br>COPY /renv.lock ./renv.lock</pre><pre># install renv &amp; restore packages                       <br>RUN Rscript -e &#39;install.packages(&quot;renv&quot;)&#39;<br>RUN Rscript -e &#39;renv::restore()&#39;</pre><pre># remove install files                       <br>RUN rm -rf /var/lib/apt/lists/*</pre><pre># make all app files readable, gives rwe permisssion (solves issue when dev in Windows, but building in Ubuntu)                       RUN chmod -R 755 /app</pre><pre># expose port (for local deployment only)                       EXPOSE 3838</pre><pre># set non-root                       <br>RUN useradd shiny_user<br>USER shiny_user</pre><pre># run app on container start (use heroku port variable for deployment)<br>CMD [&quot;R&quot;, &quot;-e&quot;, &quot;shiny::runApp(&#39;/app&#39;, host = &#39;0.0.0.0&#39;, port = as.numeric(Sys.getenv(&#39;PORT&#39;)))&quot;]</pre><p>In this Dockerfile, renv is used to install the necessary R libraries from a renv.lock file via `RUN Rscript -e ‘renv::restore()’` to have the same libray versions in the container as in the local dev environment.</p><p>To run the containerized app on Heroku, two things are necessary. First, the container must run as non-root for security reasons. Make a new user via RUN useradd shiny_user and set via USER shiny_user .</p><p>Second, Heroku provides you with a random Port via the PORT host variable for each dyno. To run the Shiny app at this port, use port = as.numeric(Sys.getenv(&#39;PORT&#39;)) in the runApp command.</p><h3>Continuous Deployment with GitHub Actions</h3><p>GitHub Actions provides an straightforward template and <a href="https://github.com/marketplace/actions/deploy-to-heroku">instructions </a>from <a href="https://github.com/AkhileshNS/heroku-deploy">https://github.com/AkhileshNS/heroku-deploy</a> to deploy to Heroku. In the top level include a directory .github/workflows with the following main.yml file in your GitHub repo:</p><pre>name: heroku_deploy<br>    on:                         <br>        push:                           <br>            branches:<br>                - master</pre><pre>jobs:                        <br>    build:                          <br>    runs-on: ubuntu-latest                        <br>       steps:<br>           - uses: actions/checkout@v2        <br>           - uses: akhileshns/heroku-deploy@v3.6.8<br>           with: <br>               heroku_api_key: ${{secrets.HEROKU_API_KEY}}  <br>               heroku_app_name: &quot;geocode-shiny&quot;                                 <br>               heroku_email: ${{secrets.HEROKU_EMAIL}}                                   <br>               healthcheck: &quot;https://geocode-shiny.herokuapp.com/&quot;                                     <br>               usedocker: true                                  <br>               delay: 60                                 <br>               rollbackonhealthcheckfailed: true</pre><pre>           env: <br>              HD_API_KEY: ${{secrets.MAPS_API_KEY}} # Docker env var</pre><p>Here, we specify the action “heroku_deploy” to happen on a push to the master branch. In the steps, the commit which triggered the action is checked out to be accessed by the workflow and in the next step it is pushed to Heroku, build and deployed.</p><p>The parameters <em>heroku_api_key, heroku_app_name</em> and <em>heroku_email</em> are needed. To get them</p><ol><li>Make an Heroku account on the website.</li><li>Go to your Heroku dashboard or <a href="https://devcenter.heroku.com/articles/heroku-cli">download the CLI tool</a>.</li><li>Create a new app with a unique name in the dashboard or via heroku create your_app_name .</li><li>Get an API key from your Heroku Account Settings or via heroku auth:token .</li><li>Store the two variables for your Heroku account in your GitHub repo Settings-&gt;Secrets as HEROKU_API_KEY and HEROKU_EMAIL.</li></ol><p>The parameter<em> usedocker: true</em> is needed for deployment of a Docker container. Additionally we use the url (which you will know after the first successful deploy) with <em>healthcheck: true </em>. The healthcheck is delayed for 60s with <em>delay: 60</em> and the deploy is rolled back to the previous commit when the health check of the app fails via <em>rollbackonhealthcheckfailed: true</em>.</p><p>This Shiny app needs a secret API key for an external API to work. It is saved as GitHub secret too and supplied as a Docker environment variable. To set env variables for your apps, prefix them with HD_. This gets stripped off in deployment and is necessary to distinguish between build and deploy variables. DO NOT put any of your secrets directly in files in GitHub repos!</p><p>That’s it! Push to the master branch (or any other, you could also use tags to specify commits for deployment in the main.yml ) and check the GitHub Actions tab if the deployment worked. Then get the URL from which your app can be reached in the dashboard or via heroku apps:info -a your_app_name . Add this url to the healthcheck in the main.yml for future deployment versions.</p><h3>Set up a custom URL for the app</h3><p>To set up a<a href="https://devcenter.heroku.com/articles/custom-domains"> custom domain for your Heroku app</a> which you own/have access to, you need to:</p><ol><li>Verify your Heroku account with a credit card. You will not occur any charges for apps on free tier and additionally would need to opt in for payed service. If you verify, you get more dynos and free dyno hours, too.</li><li>Add your domain to the app via dashboard or via the CLI tool with heroku domains:add <a href="http://www.example.com/">www.example.com</a> -a your_app_name .</li><li>Go to your Domain provider and add a new CNAME record for <a href="http://www.example.com/">www.example.com</a> to point to the Heroku DNS target you get via the dashboard or heroku domains -a your_app_name.</li><li>Check that the DNS is correctly configured via host <a href="http://www.example.com/">www.example.com</a> .</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b31003858b68" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/deploying-an-r-shiny-app-on-heroku-free-tier-b31003858b68">Deploying an R Shiny app on Heroku free tier</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Big Query with R]]></title>
            <link>https://medium.com/analytics-vidhya/google-big-query-with-r-875facef7844?source=rss-7056b9dfb238------2</link>
            <guid isPermaLink="false">https://medium.com/p/875facef7844</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-warehouse]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Tim M. Schendzielorz]]></dc:creator>
            <pubDate>Fri, 20 Mar 2020 14:11:05 GMT</pubDate>
            <atom:updated>2020-04-11T20:28:34.349Z</atom:updated>
            <content:encoded><![CDATA[<h4>Lightning fast database querying with the R API.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*0w8mCGsOdP79QEKy0A2CJQ.jpeg" /><figcaption><a href="https://blog.dotcom-monitor.com/web-page-load-speed/web-performance-analytics-https-archive-bigquery/">Source</a></figcaption></figure><p><em>This article was also published on </em><a href="https://www.r-bloggers.com/"><em>https://www.r-bloggers.com/</em></a><em>.</em></p><p><em>This is part one of a multi article series on building and deploying an API robustly with R and Docker that lets you extract live data from Google Big Query. For part two, see </em><a href="https://medium.com/analytics-vidhya/live-data-extraction-with-cron-and-r-f29324bf153e"><em>Easy and robust live data extraction with Cron and R</em></a><em>.</em></p><h3>What is Google Big Query?</h3><p><a href="https://cloud.google.com/bigquery/what-is-bigquery">Big Query</a> is a highly performant cloud data storage service which started in 2011. You can manage it inside the Google Cloud Console and query the storage with standard SQL commands from the bq console or via the API. It is easy to set up, auto scales and there are a variety of established connectors to Google and other services. In this article I will show you the advantages of working with Big Query and how to use the API from R and build queries with dplyr functions.</p><h3>What are the advantages of Big Query?</h3><p>Google Big Query has a few advantages in comparison to other cloud data storages. Other technologies will be comparable or even better, but the combination of all the advantages and especially the Google integration is what makes Big Query really outstanding. Advantages are:</p><ul><li><strong>Lightning fast query speeds: </strong>BQ had similar <a href="https://www.atscale.com/blog/tech-talk-bi-performance-benchmarks-with-bigquery-from-google/">benchmarking results</a> to other modern data base technologies. BQ was also <a href="https://fivetran.com/blog/warehouse-benchmark">compared to other Data Warehouse</a> solution that have similar features such as Amazon Redshift, Snowflake, Microsoft Azure and Presto and all showed more or less similar performances and pricing.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSkqehEluYJrGjKyaLTazg.png" /><figcaption>Big Query shows exceptional Performance with queries without GROUP BY statements (Q1) and has significant worse performance with GROUP BY statements (Q2-Q3). With many large JOINs and many GROUP BYs (Q4) it performs in the middle of the other tested technologies. <a href="https://www.atscale.com/blog/tech-talk-bi-performance-benchmarks-with-bigquery-from-google/">Source</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qvnxzbux5jzrPEt0a4RTpg.png" /><figcaption>Biq Query really shines with performance under concurrent queries. Query time stays constant in comparison to the other technologies due to fast auto scaling. <a href="https://www.atscale.com/blog/tech-talk-bi-performance-benchmarks-with-bigquery-from-google/">Source</a></figcaption></figure><ul><li><strong>Low costs:</strong> BQ has similar costs to other big data warehouse solutions. Costs as of today are 0.02$/GB per Month storage and 5$/TB data querying. 10 GB storage per month is free as well as 1 TB per month data querying. Many operations as e.g. data loading, copying, exporting, deleting as well as failed queries are free. Furthermore there is query caching, you do not have to pay if you run a query again on the same, unchanged data. There are flat-rate prices available, too.</li><li><strong>Easy integration with Google services: </strong>Data from<strong> Google Analytics 360 </strong>can be easily stored in BQ. This is a big advantage as Google Analytics has a limit on stored rows and only enables reports on sample data. You can get a more detailed customer journey and combine every dimension with every metric if you store your Analytics data in BQ as you can access all of your tracking data. Additionally, datasets on Google Cloud storage and Google Drive can be queried via BQ without manually importing the dataset.</li><li><strong>Easy integration with other tools:</strong> BQ has it’s own machine learning suite with Big Query ML engine which enables you to import tensorflow models for prediction. There also is a BQ BI engine, but both seem not particularly useful to me yet as the functionalities are limited. Many services such as Tableau, Qlik or Looker have connectors to BQ.</li><li><strong>No-Ops management:</strong> No prior data base management knowledge is needed to set up BQ and manage security and recovery.</li><li><strong>Public datasets: </strong>You have a nice selection of publicly available data on BQ, some of the datasets are constantly updated!</li></ul><h3>Use Big Query with R</h3><h4>Enable Big Query and get your credentials</h4><ol><li>Go to the <a href="https://console.cloud.google.com/">Google Cloud Platform </a>and login with your Google account. At the top left corner go to “Choose Project” and start a new project. If you go on your home dashboard to “Go to APIs overview” you will see the activated APIs of the Google Cloud Service. “BigQuery API” and “BigQuery Storage API” should be activated by default for all new projects.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aTeAY560rFnBKx_89rfung.jpeg" /><figcaption>Activated APIs for a new Google Cloud project.</figcaption></figure><p>2. Get your API key as described by the gargle R package <a href="https://gargle.r-lib.org/articles/get-api-credentials.html">here</a>. In short, go to the Credentials section at the Google Cloud Platform in the dashboard shown above and create credentials &gt; API key. You can rename your API key and restrict it to only certain APIs like “BigQuery API”. If you need application access to BQ you will need a <a href="https://gargle.r-lib.org/articles/get-api-credentials.html">service account token</a> which you can download as JSON.</p><h4>Querying with R</h4><p>For querying BQ we will use the R library <a href="https://github.com/r-dbi/bigrquery">bigrquery</a>. The other prominent R library for BQ is <a href="https://code.markedmondson.me/bigQueryR/">bigQueryR</a> which in contrast to bigrquery depends on library <a href="https://github.com/MarkEdmondson1234/googleAuthR">googleAuthR</a> which makes it more compatible with Shiny and other packages.</p><p>First, we get the libraries and authenticate either with our created API key or with the downloaded service account token JSON.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/943f918f8d6fcc4a0e23eaea491155c3/href">https://medium.com/media/943f918f8d6fcc4a0e23eaea491155c3/href</a></iframe><p>Now we can start querying our Big Query data or public datasets. We will query the Real-time Air Quality dataset from <a href="https://openaq.org/#/?_k=h8s64f">openAQ</a>. This is an open source project which provides real time data (if you stretch the definition of “real time) from 5490 world wide air quality measurement stations, which is awesome! You can see the dataset and a short description on Big Query <a href="https://console.cloud.google.com/bigquery?p=bigquery-public-data&amp;d=openaq&amp;page=dataset&amp;project=">here</a> if you are logged into Google. To find open datasets in the Cloud Console, scroll down on the left menu, there you should see “Big Query” under the header “Big Data”. If you go then to “+Add Data” you will be able to browse public data sets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HkivOfKVIeKTHgpHqS0JiA.png" /><figcaption>The schema of the public global air quality data table we are going to query shown in the BigQuery cloud console.</figcaption></figure><p>We will wrap the bigrquery API with DBI to be able to use it with dplyr verbs, however the <a href="https://bigrquery.r-dbi.org/">bigrquery</a> package provides an low level API, too.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20c4648d720d8a2425e1c2c5dde9c82d/href">https://medium.com/media/20c4648d720d8a2425e1c2c5dde9c82d/href</a></iframe><p>In this example you can see querying with dplyr functions that are converted to SQL queries, however you can do not get the full flexibility that direct SQL querying provides. For this you could send SQL queries via DBI::dbGetQuery() from R. The global air quality data set gets updated regularly, however older entries are omitted, probably to save storage costs. Check out my next post on how to build a Dockerized Cron-job to get the newest air pollution data from India while keeping older records.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=875facef7844" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/google-big-query-with-r-875facef7844">Google Big Query with R</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Shiny Flexdashboard with Docker]]></title>
            <link>https://medium.com/analytics-vidhya/deploying-a-shiny-flexdashboard-with-docker-cca338a10d12?source=rss-7056b9dfb238------2</link>
            <guid isPermaLink="false">https://medium.com/p/cca338a10d12</guid>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[shiny]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Tim M. Schendzielorz]]></dc:creator>
            <pubDate>Tue, 21 Jan 2020 12:35:47 GMT</pubDate>
            <atom:updated>2020-12-07T09:47:34.022Z</atom:updated>
            <content:encoded><![CDATA[<h4>Robust deployment of beautiful dashboards.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DtD0j_tL_QwNpmCtZ3Rs0g.png" /><figcaption>Example Flexdashboard. From <a href="https://walkerke.shinyapps.io/neighborhood_diversity/">shinyapps.io</a></figcaption></figure><p><em>This is part two of a growing series on data reporting with micro services. For building this dashboard see part one, </em><a href="https://medium.com/analytics-vidhya/shiny-dashboards-with-flexdashboard-e66aaafac1f2"><strong><em>Shiny Dashboards with Flexdashboard</em></strong></a><em>. For deploying dashboards at scale in production with a Shiny Proxy server, see part three.</em></p><p><em>This article was also published on </em><a href="https://www.r-bloggers.com/"><em>https://www.r-bloggers.com/</em></a><em>.</em></p><p>Dashboards are a fantastic way to deliver data insights fast, intelligible and consistently. Besides designing aesthetic and useful dashboards, a major challenge is deployment. In most businesses, several people besides Data Analysts and various technologies are involved. This leads to a slow deployment process and time consuming dependency management. In this article, we will learn how to containerize a <a href="https://medium.com/analytics-vidhya/shiny-dashboards-with-flexdashboard-e66aaafac1f2">previously</a> build <a href="https://timosch.shinyapps.io/dashboard_example/"><strong>R Flexdashboard</strong></a><strong> with Shiny reactivity </strong>with Docker to make a web app that is more easily to reproduce, deploy, scale and manage.</p><h3>Why Docker?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*VIfwIv89V0zesAgLvT6ExQ.png" /><figcaption><a href="https://ertan-toker.de/docker-container-mongodb/">Source</a></figcaption></figure><p><a href="https://www.docker.com/why-docker">Docker</a> is the one of the fastest growing open source technologies as of today. Docker containers are sandbox environments for running applications. Instead of emulating a whole machine, only a Linux OS plus libraries is emulated. Such container is more lightweight than a Virtual Machine and running applications containerized has a lot of advantages. Only resources assigned to the container are used and the environment for your application is always the same, regardless on which host it is deployed. That makes Docker the favorite tool for many companies to deploy reproducible and secure applications. An application is more efficient to manage and debug if it runs isolated in a container with defined connections to other containers and the host. Additionally, software is faster to set up due to reduced dependency issues and easy to scale. Furthermore standardized build, test and deployment environments enable fast and robust CI/CD cycles for software development. Various services and applications can be managed and load balanced via container orchestration tools, for example <a href="https://docs.docker.com/engine/swarm/key-concepts/">Docker Swarm</a> or <a href="https://kubernetes.io/de/">Kubernetes</a>.</p><h3>Building the Docker container</h3><h4>Get started</h4><p>Containers are build from images which are defined by instructions in a Dockerfile. For each instruction an intermediate image is build and used as base image to build upon. There are already a lot of ready to use images available for download on <a href="https://hub.docker.com/">Dockerhub</a>. You can use these images as base for your own image, too. After you <a href="https://docs.docker.com/install/">installed Docker</a> for your host system, you can download public images via docker pull in your terminal. We will build the container for the Shiny Flexdashboard upon Open Analytics <a href="https://hub.docker.com/r/openanalytics/r-shiny">R Shiny image</a>. This image contains basic R, necessary linux libraries and the Shiny and Rmarkdown R packages. You can see their <a href="https://github.com/openanalytics/r-shiny/blob/master/Dockerfile">corresponding Dockerfile on GitHub</a>. You can download the image via docker pull openanalytics/r-shiny.</p><h4>The Dockerfile</h4><p>You can check out this Dockerfile and the file for the Shiny Flexdashboard in my <a href="https://github.com/timosch29/Dockerized-Shiny-Proxy-Server/tree/master/example_dashboard"><strong>GitHub repo</strong></a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ec4bb03fd00a890c0cbe754ffd2373d/href">https://medium.com/media/7ec4bb03fd00a890c0cbe754ffd2373d/href</a></iframe><p>The Dockerfile specifies how the image is build and in what sequence. FROM openanalytics/r-shiny specifies the base container image, the instructions after are explained with comments. You can get an overview of Dockerfile instructions in the <a href="https://docs.docker.com/engine/reference/builder/">Docker documentation</a> or on this <a href="https://kapeli.com/cheat_sheets/Dockerfile.docset/Contents/Resources/Documents/index">cheat sheet</a>. If you do not have an Flexdashboard Rmd file and want to deploy just a Shiny app, you have to alter the CMD instruction at the end either like <a href="https://github.com/TelethonKids/deploy_shiny_app/blob/master/webapp/Dockerfile">this</a> or as described in this <a href="https://medium.com/@suomynonascitylana/getting-started-with-docker-to-do-data-science-and-deploy-a-shiny-app-46803f8a0a69">medium article</a>.</p><h4>Build the image</h4><p>An image is build from the Dockerfile with command docker build. If you have cloned my GitHub repo, run following command in the directory of the Dockerfile <strong>docker build -t example_dashboard .</strong>, this will build the image from the Dockerfile and name it <em>example_dashboard</em>. The build process will run quite a few minutes the first time as you download and install the dependencies. The nice thing is, once you completed a step it is cached and you do not have to run it completely when you change other steps in your Dockerfile or you can even use the same cached step for another Docker image. You can see all available images on your host with docker image ls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ULW0lVbjph6SMEwwMpUwIg.png" /><figcaption>Terminal output of the Docker image building</figcaption></figure><h4>Run the container</h4><p>To make a container from an image use command docker create and use command docker start with the name of the image to start a container. Conveniently, there is a command which combines both into one that we will use here, docker run. This command will even try to pull images from <a href="https://hub.docker.com/">Docker Hub</a> if it can not find the image name on your host.</p><p>We spin up the container with <strong>docker run --name=example_dashboard_container --rm -p 3838:3838 example_dashboard</strong>. This maps the (previously exposed) port 3838 from the Docker container to the same port 3838 of the host machine. Parameter --rm indicates that we want the container to be removed if it was stopped and we specify the container name (which is not necessary) with --name=. If you want to be able to use your terminal further, set parameter -d for running in detached mode. You can still view the container output via docker logs example_dashboard_container.</p><p>You can then access the Shiny Flexdashboard inside the Docker container rendered by your browser by navigating to <a href="http://localhost:3838/"><strong>http://localhost:3838</strong></a>. Et voilà, you see the locally deployed Flexdashboard with Shiny elements which will always give the same results, no matter on which machine it is deployed and without having to manage dependencies and versions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OGwJfmSoLNE-C92l5QPTBw.gif" /><figcaption>The deployed example dashboard. Try it out out on <a href="https://timosch.shinyapps.io/dashboard_example/">Shinyapps.io</a></figcaption></figure><h4>Deploy the container</h4><p>For deploying the container with the Flexdashboard, you could build the image again from the Dockerfile on your own server with a Docker installation. Way more convenient is it to save your image via docker save -o ~/example_dashboard.tar example_dashboard and copy the file to your server. Then load the image via docker load -i example_dashboard.tar and run the container from it. You can reach the dashboard with the IP address of your server instead of localhost in your browser. If you have a domain, you can also add it so your dashboard can be reached through it.</p><p>You can set up a reverse proxy like <strong>nginx </strong>that routes your traffic to various containers depending on the subdomain. Yes, there is<a href="https://github.com/jwilder/nginx-proxy"> a Docker image</a> for that, too.</p><p>How to deploy Docker containers to a cloud provider is well documented and you will find instructions and community examples on the web, e.g. for <a href="https://www.ybrikman.com/writing/2015/11/11/running-docker-aws-ground-up/"><strong>AWS</strong></a>, <a href="https://blog.machinebox.io/deploy-docker-containers-in-google-cloud-platform-4b921c77476b"><strong>Google Cloud</strong></a> and <a href="https://blog.machinebox.io/deploy-machine-box-in-digital-ocean-385265fbeafd"><strong>DigitalOcean</strong></a>. For deploying your Shiny app on Heroku free tier, see this article: <a href="https://medium.com/analytics-vidhya/deploying-an-r-shiny-app-on-heroku-free-tier-b31003858b68">https://medium.com/analytics-vidhya/deploying-an-r-shiny-app-on-heroku-free-tier-b31003858b68</a>. If you want to deploy a Shiny app/Flexdashboard at scale in a professional setting, a valuable open source tool is the <a href="https://www.shinyproxy.io/">Shinyproxy</a> server from OpenAnalytics. For deploying apps with Shinyproxy, please see part three of this series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cca338a10d12" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/deploying-a-shiny-flexdashboard-with-docker-cca338a10d12">Deploying a Shiny Flexdashboard with Docker</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A guide to Data Transformation]]></title>
            <link>https://medium.com/analytics-vidhya/a-guide-to-data-transformation-9e5fa9ae1ca3?source=rss-7056b9dfb238------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e5fa9ae1ca3</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-wrangling]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Tim M. Schendzielorz]]></dc:creator>
            <pubDate>Wed, 15 Jan 2020 15:17:27 GMT</pubDate>
            <atom:updated>2024-02-20T08:35:57.683Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn when and how to transform your variables for better insights.</h4><figure><img alt="A sweet Transformer statue" src="https://cdn-images-1.medium.com/max/1024/1*PW51r1DTgfFk_xmTKen3wA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@tetrakiss?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Arseny Togulev</a> on <a href="https://unsplash.com/s/photos/transformer?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><em>This article was also published on </em><a href="https://www.r-bloggers.com/"><em>https://www.r-bloggers.com/</em></a><em>.</em></p><p><em>I have two series online about more data infrastructure related topics, the first one is about </em><strong><em>building and robustly deploying a Shiny Flexdashboard with Docker </em></strong><em>(</em><a href="https://medium.com/analytics-vidhya/shiny-dashboards-with-flexdashboard-e66aaafac1f2"><em>Link to Part I</em></a><em>). The second one is about</em><strong><em> building and robustly deploying an API for extracting live data from Google Big Query</em></strong><em> (</em><a href="https://medium.com/analytics-vidhya/google-big-query-with-r-875facef7844"><em>Link to Part I</em></a><em>).</em></p><h3>What is Data Transformation?</h3><p>Data Transformation in a statistics context means the application of a mathematical expression to each point in the data. In contrast, in a Data Engineering context Transformation can also mean transforming data from one format to another in the <a href="https://www.analyticsvidhya.com/blog/2022/05/an-introduction-on-etl-tools-for-beginners/?utm_source=Backlink&amp;utm_medium=SEO"><strong>Extract Transform Load</strong></a> (ETL) process.</p><h4>Why should I transform my data?</h4><ul><li><strong>Improve interpretability.</strong> Some variables are not in the format we need for a certain question, e.g. car manufactures supply miles/gallon values for fuel consumption, however for comparing car models we are more interested in the reciprocal gallons/mile.</li><li><strong>De-clutter graphs. </strong>If you visualize two or more variables that are not evenly distributed across the parameters, you end up with data points close by. For a better visualization it might be a good idea to transform the data so it is more evenly distributed across the graph. Another approach could be to use a different scale on your graph axis.</li><li><strong>To get insight about the relationship between variables.</strong> The relationship between variables is often not linear but of a different type. Common example is taking the log of income to compare it to another variable as the utility of more income diminishes with higher income. (See this excellent discussion about the highly utilized log- transform on <a href="https://stats.stackexchange.com/questions/18844/when-and-why-should-you-take-the-log-of-a-distribution-of-numbers">Cross Validated</a>.) Another example is the polynomial growth of money on an bank account with interest rate compared to time. To calculate a simple <a href="https://en.wikipedia.org/wiki/Correlation_coefficient">correlation coefficient</a> between variables, the variables need to show a linear relationship. To meet this criteria, you might be able to transform one or both variables.</li><li><strong>To meet assumptions for statistical inference.</strong> When constructing simple confidence intervals, the assumption is that the data is normally distributed and not skewed left or right. For <a href="https://www.analyticsvidhya.com/blog/2021/10/everything-you-need-to-know-about-linear-regression/?utm_source=Backlink&amp;utm_medium=SEO"><strong>linear regression analysis</strong></a> an important assumption is <a href="https://en.wikipedia.org/wiki/Homoscedasticity">homoscedasticity,</a> meaning that the error variance of your dependent outcome variable is independent from your predictor variables. An assumption for many statistical test as the T-test is that the errors of a model ( the values of a measurement sampled from a population) are normally distributed.</li></ul><h4>Important distinctions</h4><p>It is important to know what we are talking about when we use the term transformation. Transformation, normalization and standardization are often used interchangeably and wrongly so.</p><ul><li><strong>Normalization </strong>is the process of scaling in respect to the entire data range so that the data has a range from 0 to 1.</li><li><strong>Standardization </strong>is the process of transforming in respect to the entire data range so that the data has a mean of 0 and a standard deviation of 1. It’s distribution is now a Standard Normal Distribution.</li><li><strong>Transformation </strong>is the application of the same calculation to every point of the data separately.</li></ul><p>Standardization transforms the data to follow a Standard Normal Distribution (left graph). Normalization and Standardization can be seen as special cases of Transformation. To demonstrate the difference between a standard normal distribution and a standard distribution we simulate data and graph it:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fplot.ly%2F%7Etimosch%2F1%2F&amp;src=https%3A%2F%2Fplot.ly%2F%7Etimosch%2F1.embed%3Fautosize%3Dtrue&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8365a0bccaa6ed1ffd127a2879e3e9b/href">https://medium.com/media/d8365a0bccaa6ed1ffd127a2879e3e9b/href</a></iframe><p><a href="https://github.com/timosch29/Medium_Data_Transformation_with_R/blob/master/Plot%20Normal%20Distributions.R">R Code for the Plotly graphs</a> above. Interactive Plotly graphs are embedded via plot.ly hosting, but could also be embedded from Github Pages via an iframe, see <a href="https://towardsdatascience.com/how-to-create-a-plotly-visualization-and-embed-it-on-websites-517c1a78568b">this article</a> for instructions.</p><h3>How to transform data?</h3><p>To get insights, data is most often transformed to follow close to a normal distribution either to meet statistical assumptions or to detect linear relationships between other variables. One of the first steps for those techniques is to check how close the variables already follow a normal distribution.</p><h4><strong>How to check if your data follows a normal distribution?</strong></h4><p>It is common to inspect your data visually and/or check the assumption of normality with a statistical test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gLM4dB4nmbVp5WF7iv9Htg.png" /><figcaption>Variable distribution histogram and corresponding QQ-plot with reference line of a perfect normal distribution. From <a href="http://www.ucd.ie/ecomodel/Resources/QQplots_WebVersion.html">UCD</a></figcaption></figure><p>To <strong>visually explore </strong>the distribution of your data, we will look at the density plot as well as a simple <strong>QQ-plot</strong>. The QQ-plot is an excellent tool for inspecting various properties of your data distribution and asses if and how you need to transform your data. Here the quantiles of a perfect normal distribution are plotted against the quantiles of your data. Quantiles measure at which data point a certain percentage of the data is included. For example, the data point of the 0.2 quantile is the point where 20% of the data is below and 80% is above. A reference line is drawn which indicates how the plot would look if your variable would follow a perfect normal distribution. The closer your points in the QQ-plot are to this line, the more likely it is that your data follows a normal distribution and does not need additional transformation.</p><p>For a <strong>statistical analysis</strong> of normality of your data, commonly used tests are the Shapiro-Wilk-Test or the Kolmogorov-Smirnov-Test. The SW Test has generally a higher detection power, the non-parametric KS Test should be used with a high number of observations. Generally speaking, those tests calculate how likely it is that your data distribution is similar to a normal distribution (Technically, how likely it is that you do not err with H0- the hypothesis that the data is normally distributed). These tests however have the well known problems of Frequentist Null Hypothesis Testing, which is not in the scope of this article to discuss, i.e. the problem of being too sensitive with a huge amount of observations. The KS test is generally too sensitive to points in the middle of the data distribution in comparison to the more important tails. Additionally, those tests can not tell you how problematic a non-normality would be for getting insights from your data. Because of this, <strong>I would advise to use an exploratory, visual approach to check your data distribution and forego any statistical testing</strong> if you do not need this for an automated script.</p><h4>Data distributions and their corresponding QQ-plots</h4><p>The following diagrams show simulated data with the density distribution and the corresponding QQ-plot. Four strong and typical deviations from a normal distribution are shown. Only for the normally distributed data an additional statistical test for normality is shown in the code snippet for completeness.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fplot.ly%2F%7Etimosch%2F3%2F&amp;src=https%3A%2F%2Fplot.ly%2F%7Etimosch%2F3.embed%3Fautosize%3Dtrue&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7789de66f619dea333136aaf9095172/href">https://medium.com/media/b7789de66f619dea333136aaf9095172/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/394736d92ccb0e3cb8d9cd2515427bbb/href">https://medium.com/media/394736d92ccb0e3cb8d9cd2515427bbb/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fplot.ly%2F%7Etimosch%2F5%2F&amp;src=https%3A%2F%2Fplot.ly%2F%7Etimosch%2F5.embed%3Fautosize%3Dtrue&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/a70ef3084fbfced088f6484976f35924/href">https://medium.com/media/a70ef3084fbfced088f6484976f35924/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fplot.ly%2F%7Etimosch%2F7%2F&amp;src=https%3A%2F%2Fplot.ly%2F%7Etimosch%2F7.embed%3Fautosize%3Dtrue&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/f95a46ac3a93be42ba720abe986364c9/href">https://medium.com/media/f95a46ac3a93be42ba720abe986364c9/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fplot.ly%2F%7Etimosch%2F9%2F&amp;src=https%3A%2F%2Fplot.ly%2F%7Etimosch%2F9.embed%3Fautosize%3Dtrue&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/155eccabefd07b5a94f81e942b88ea90/href">https://medium.com/media/155eccabefd07b5a94f81e942b88ea90/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fplot.ly%2F%7Etimosch%2F11%2F&amp;src=https%3A%2F%2Fplot.ly%2F%7Etimosch%2F11.embed%3Fautosize%3Dtrue&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=plot" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/24a9ed1cfcd70b27ed43a8b893a79773/href">https://medium.com/media/24a9ed1cfcd70b27ed43a8b893a79773/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/723fdc13b6560d78b4501ba4ba62cbd4/href">https://medium.com/media/723fdc13b6560d78b4501ba4ba62cbd4/href</a></iframe><p>For playing around with distributions and their corresponding QQ-plots I can recommend <a href="https://xiongge.shinyapps.io/QQplots/">this nice little R <strong>shiny app</strong></a> from Cross Validated user <a href="https://stats.stackexchange.com/questions/101274/how-to-interpret-a-qq-plot/185070#185070">Zhanxiong</a>.</p><h4><strong>Which transformation to pick?</strong></h4><p>If you decide that your data should follow a normal distribution and needs transformation, there are simple and highly utilized power transformations we will have a look at. They transform your data to follow a normal distribution more closely. It is however important to note, that <strong>when transforming data you will lose information about the data generation process and you will lose interpretability of the values, too.</strong> You might consider to back-transform the variable at a certain step in your analysis. <strong>Generally speaking, the expression for transformation which matches data generation is suited best.</strong> Logarithm should be used if data generation effects were multiplicative and the data follows order of magnitudes. Roots should be used if the data generation involved squared effects.</p><h4>Simple Transformations</h4><p>For transformation multiply every data point with one of the following expression. The<strong> </strong>expressions are sorted from weakest effect to strongest. If your transformation of choice is too strong, you will end up with data skewed in the other direction.</p><p><strong>Right (positive) skewed data:</strong></p><ul><li><strong>Root <em>ⁿ√x. </em></strong>Weakest transformation, stronger with higher order root. For negative numbers special care needs to be taken with the sign while transforming negative numbers:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70682b6e2c9a727163ac0d793fff0d13/href">https://medium.com/media/70682b6e2c9a727163ac0d793fff0d13/href</a></iframe><ul><li><strong>Logarithm <em>log(x). </em></strong>Commonly used transformation, the strength of this transformation can be somewhat altered by the root of the logarithm. It can not be used on negative numbers or 0, here you need to shift the entire data by adding at least <em>|min(x)|+1.</em></li><li><strong>Reciprocal</strong> <strong><em>1/x.</em></strong> Strongest transformation, the transformation is stronger with higher exponents, e.g. <em>1/x³</em>. This transformation should not be done with negative numbers and numbers close to zero, hence the data should be shifted similar as the log transform.</li></ul><p><strong>Left (negative) skewed data</strong></p><ul><li><strong>Reflect Data and use the appropriate transformation for right skew. </strong>Reflect every data point by subtracting it from the maximum value. Add 1 to every data point to avoid having one or multiple 0 in your data.</li><li><strong>Square <em>x². </em></strong>Stronger with higher power. Can not be used with negative values.</li><li><strong>Exponential <em>eˣ. </em></strong>Strongest transformation and can be used with negative values. Stronger with higher base.</li></ul><p><strong>Light &amp; heavy tailed data</strong></p><ul><li><strong>Subtract the data points from the median and transform. </strong>Deviations of the tail from normality are usually less critical than skewness and might not need transformation after all. The subtraction from the median sets your data to a median of 0. After that use an appropriate transformation for skewed data on the absolute deviations from 0 on either side. For <strong>heavy-tailed</strong> data use transformations for right skew to pull in on the median and for <strong>light-tailed </strong>data use transformations for left skew to push data away from the median.</li></ul><h4>Automatic Transformations</h4><p>There are various implementations of automatic transformations in R that choose the optimal transformation expression for you. They determine a <em>lambda </em>value which is the power coefficient used to transform your data closest to a normal distribution.</p><ul><li><strong>Use Lambert W x Gaussian transform.</strong> The R package <a href="https://cran.r-project.org/web/packages/LambertW/index.html">LambertW</a> has an implementation for automatically transforming heavy or light tailed data with Gaussianize().</li><li><strong>Tukey’s Ladder of Powers. </strong>For skewed data<strong>, </strong>the <a href="https://rdrr.io/cran/rcompanion/man/transformTukey.html">implementation</a> transformTukey()from the R package rcompanion uses Shapiro-Wilk tests iteratively to find at which <em>lambda</em> value the data is closest to normality and transforms it. Left skewed data should be reflected to right skew and there should be no negative values.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/0*zc7Cppgs5ev6OlUD.jpg" /><figcaption>Tukey’s Ladder of Powers <em>lamda values and corresponding power transforms. Lambda values can be decimal. </em><a href="http://onlinestatbook.com/2/transformations/tukey.html"><em>Source</em></a></figcaption></figure><ul><li><strong>Box-Cox Transformation.</strong> The <a href="https://rdrr.io/cran/forecast/man/BoxCox.lambda.html">implementation</a> BoxCox.lambda()from the R package forecast finds iteratively a <em>lambda </em>value which maximizes the log-likelihood of a linear model. However it can be used on a single variable with model formula <em>x~1</em>. The transformation with the resulting <em>lambda </em>value can be done via the forecast <a href="https://rdrr.io/cran/forecast/man/BoxCox.html">function </a>BoxCox(). There is also an implementation in the R package MASS. Standard Box-Cox can not be used with negative values, two-parameter Box-Cox however can.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o7TKVFCdpZD0nThEk%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o7TKVFCdpZD0nThEk%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3o7TKVFCdpZD0nThEk%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="241" frameborder="0" scrolling="no"><a href="https://medium.com/media/b628aa33a882aab698ff5a892595e910/href">https://medium.com/media/b628aa33a882aab698ff5a892595e910/href</a></iframe><ul><li><strong>Yeo-Johnson Transformation. </strong>This can be seen as an useful extension to the Box-Cox. It is the same as Box-Cox for non-negative values and handles negative and 0 values as well. There are various implementations in R via packages <a href="https://www.rdocumentation.org/packages/car/versions/3.0-6/topics/bcPower">car</a>, <a href="https://www.rdocumentation.org/packages/VGAM/versions/1.1-2/topics/yeo.johnson">VGAM </a>and <a href="https://tidymodels.github.io/recipes/reference/step_YeoJohnson.html">recipes</a> in the meta machine-learning framework tidymodels.</li></ul><h3>Concluding remarks</h3><p>This guide provides an overview over an important data preprocessing technique, data transformation. It demonstrates why you want to transform your data during analysis. It explains how you can detect if your data needs transformation to meet the most common requirement to data distribution of normality and transform it accordingly. It shows which mathematical expression to use for transformation for stereotypical cases of non-normality and how to automate this. There are a few advanced cases for transformation, e.g. for multimodal distributions which is not covered here.</p><p>A word of caution must be given, however. There are no definitive rules when and how to transform your data. It depends on how the data was generated (and how much you do know about this), what insights you want to generate from it, how important interpretability is and how much the data distribution deviates from your desired distribution, which will be in the majority of cases a normal distribution. Hence, some<strong> closing advice for data transformation</strong>:</p><ul><li>Decide if the insights you will get from transforming are worth the downsides. E.g. decide if being able to do statistical modelling, applying a geometric technique such as k-means clustering, being able to better compare ratios or just de-clutter your graphs is worth losing direct interpretability.</li><li>Decide if an alternative approach instead satisfies your analysis. <strong>Generally speaking, finding an appropriate model to use with the raw data, e.g. quantile, spline or weighted-least-squares regression or nonparametric models for non linear relationships should be preferred instead of transformation. </strong>Alternatively you could remove outliers, however you should remember that you need a quite good reason to delete measurements.</li><li>Before and after transformation, check your distribution with a QQ-plot, even with an automatic transformation approach.</li><li>Make it clear when and why you use a transformation for reproducibility.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e5fa9ae1ca3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/a-guide-to-data-transformation-9e5fa9ae1ca3">A guide to Data Transformation</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shiny Dashboards with Flexdashboard]]></title>
            <link>https://medium.com/analytics-vidhya/shiny-dashboards-with-flexdashboard-e66aaafac1f2?source=rss-7056b9dfb238------2</link>
            <guid isPermaLink="false">https://medium.com/p/e66aaafac1f2</guid>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[shiny]]></category>
            <dc:creator><![CDATA[Tim M. Schendzielorz]]></dc:creator>
            <pubDate>Sat, 11 Jan 2020 16:31:33 GMT</pubDate>
            <atom:updated>2020-04-10T11:43:47.076Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>Build beautiful dashboards rapidly.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M2-xx451iCTugj5du3scdg.png" /><figcaption>Example Flexdashboard. From <a href="https://walkerke.shinyapps.io/neighborhood_diversity/">shinyapps.io</a></figcaption></figure><p><em>This is part one of a growing series on data reporting with micro services. For deploying web apps and this Flexdashboard in particular see part two, </em><a href="https://medium.com/analytics-vidhya/deploying-a-shiny-flexdashboard-with-docker-cca338a10d12"><strong><em>Deploying a Shiny Flexdashboard with Docker</em></strong></a><em>. For deploying dashboards at scale in production with a Shiny Proxy server, see part three.</em></p><p><em>This article was also published on </em><a href="https://www.r-bloggers.com/"><em>https://www.r-bloggers.com/</em></a><em>. Updated 2020–04–10 with short advice on performance improvement.</em></p><p>Most modern businesses rely on data. The demand is ever growing for skilled people who can supply <strong>accurate, relevant and intelligible data insights consistently and fast</strong>. Those needs are hard to meet and more often than not at stake with each other. They can be met through supplying interactive data dashboards which are mostly used for internal business KPIs, but can also be used as a way to interact with stored data, as a <a href="https://medium.com/better-programming/real-life-use-cases-of-dashboards-with-actual-roi-a8d07e36f530">sales platform or as production tool</a>. <strong>R Shiny</strong> is a convenient framework for producing reactive and powerful dashboards. I will show you how to easily make beautiful dashboards with Shiny reactivity in R via the flexdashboard package.</p><p>The basic <a href="https://timosch.shinyapps.io/dashboard_example/">Flexdashboard</a> with Shiny elements we are going to build in this article:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OGwJfmSoLNE-C92l5QPTBw.gif" /><figcaption>GIF with <a href="https://www.getcloudapp.com/">CloudApp</a>. Try out the Flexdashboard on <a href="https://timosch.shinyapps.io/dashboard_example/#section-test-plotly-and-shiny-elements">Shinapps.io</a>.</figcaption></figure><h3>Why Flexdashboard?</h3><p>A <a href="https://rmarkdown.rstudio.com/flexdashboard/">Flexdashboard </a>is build from an Rmarkdown file. Rmarkdown is a powerful framework for generating reports as HTML, PDF, Word documents, as a slideshow or make whole websites. If you are familiar with Rmarkdown, you already now how easy it is to style documents with Markdown syntax and CSS. There is a plethora of interactive <a href="https://www.htmlwidgets.org/">HTML Widgets</a> you can use with an RMarkdown file rendered to HTML like interactive <a href="https://datatables.net/extensions/">Data Tables</a> or various <a href="https://plot.ly/r/">Plotly</a> graphs, and link data points across HTML Widgets via <a href="https://rstudio.github.io/crosstalk/">crosstalk</a>. In essence, a Flexdashboard is an HTML report, but adds conveniently styled dashboard or slideshow elements. More important, you can use <strong>Shiny </strong>reactive elements and make it a full reactive web app when hosted on a server. Alternatively you can use a Flexdashboard rendered to an HTML file as a static report in dashboard format.</p><h3>Building the Flexdashboard</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BdNccJeP45i68CokoGVHyw.jpeg" /></figure><p>First, install the R library flexdashboard . If you make a new R Markdown document you now will have a Flexdashboard template from which you can create your document. Flexdashboards are defined by a YAML header which we will have a look at. Options in the YAML header will configure many details of your Flexdashboard, we will only go over the most important ones here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f81dc4e25c66f5332f2226611ca3d1e/href">https://medium.com/media/1f81dc4e25c66f5332f2226611ca3d1e/href</a></iframe><p><strong>output:</strong></p><ul><li><strong>flex_dashboard:</strong> defines the format</li><li>orientation: if dashboard elements are ordered in row or columns</li><li>social: how and if social sharing links should be embedded</li><li>theme: bootswatch styling theme, 14 themes available</li><li>source_code: if and how the source R code should be available</li><li>There are variuos other important output options not used here, just to name a few examples, css: add custom CSS style, vertical_layout: enable scrolling, logo: add logo to your dashboard</li></ul><p><strong>runtime:</strong></p><ul><li><strong>shiny: </strong>enables running reactive Shiny elements</li></ul><h4>Structuring the Flexdashboard</h4><p>Level 2 Markdown headers --------------- define either row and columns with associated widths/heights. If no widths/heights are defined the rows and columns are split equally. Level 3 headers ### split elements further inside a row or column. You can also use {.tabset}as in an Rmarkdown document at every level to get tabsets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0fV9CIBfpw-m0PiP.png" /><figcaption>Tabset example. From <a href="https://rmarkdown.rstudio.com/flexdashboard/using.html#tabsets">Rstudio Flexdashboard guide</a></figcaption></figure><p>For a multiple page Flexdashboard use Level 1 header ============= to define pages. You can overwrite the element orientation from the YAML header with {data-orientation= } and give it an icon with {data-icon= }. Headers of every level can be linked as in Rmarkdown with [linktext](#headername).</p><p>We will create a two page dashboard. The first page has one row partitioned into two columns of unequal sizes for demonstration purpose. The second page has a default input sidebar with fixed color and width on the left and one big element on the right. Note that I do not necessarily need to give a a data-width argument here and that you can define a global input sidebar for all dashboard pages if you define the sidebar on Level 1.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/584a8ff751aa11421a6cdd1b934609bd/href">https://medium.com/media/584a8ff751aa11421a6cdd1b934609bd/href</a></iframe><h4>The dashboard content</h4><p>We will make the<a href="https://beta.rstudioconnect.com/jjallaire/htmlwidgets-d3heatmap/htmlwidgets-d3heatmap.html"> NBA example Flexdashboard</a> from user jjallaire on the first dashboard page to demonstrate HTML widget functionality. The first code chunk is for loading the necessary R libraries and importing the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cff59d41c9528cccb9131543657f23f/href">https://medium.com/media/3cff59d41c9528cccb9131543657f23f/href</a></iframe><p>On the second page we will demonstrate basic Shiny reactivity. We will make an input button in a sidebar on the left, which reacts on button press with rendering a <a href="https://plot.ly/r/">Plotly</a> interactive graph. We insert a progress bar in the reactive function with withProgress(message= , value= {function}) and increment the progress bar with incProgress(). This element adds to the user experience, especially when rendering graphs or importing data takes long. Try out the button reactivity in the embedded dashboard on top! You can find the complete code on my <a href="https://github.com/timosch29/Dockerized-Shiny-Proxy-Server/blob/master/example_dashboard/dashboard_example.Rmd">GitHub repo</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b4f5364c1a842a35a138c31457d0702/href">https://medium.com/media/8b4f5364c1a842a35a138c31457d0702/href</a></iframe><h3><strong>Deployment</strong></h3><p>Now we can view the dashboard locally for testing it. You can either use the “Run” button in Rstudio to render the Rmd file and open it in your browser in the Viewer pane, or do this manually via the R command rmarkdown::run(&quot;pathto/dashboard_example.Rmd&quot;, shiny_args = list(port = 3838, host = &quot;0.0.0.0&quot;)). Then you reach the dashboard in your webbrowser via http://localhost:3838 or any other host and port you defined via shiny_args.</p><p>You can also render the Rmd file to a static HTML file with command rmarkdown::render(&quot;pathto/dashboard_example.Rmd&quot;). The advantage is that you can send the file as report via email, either as link, attached file or even embedded in the body of the mail. The option to make slides in Flexdashboard and make a static report can be a great way to present your analytics results. The big disadvantage is that you can not use Shiny reactivity. See page two of the below embedded static HTML file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1JCh873p5t7ocBTyhMipag.gif" /><figcaption>Static Flexdashboard. Shiny reactivity does not work, however interactive widgets are possible. Try it out on <a href="https://timosch29.github.io/Dockerized-Shiny-Proxy-Server/example_dashboard/dashboard_example#section-test-html-widget">Github pages</a>.</figcaption></figure><p><em>If you find this article useful do not forget to clap those hands and follow me for more!</em></p><h4>Basic web deployment</h4><p>For a<a href="https://timosch.shinyapps.io/dashboard_example/#section-test-plotly-and-shiny-elements"> reactive web app</a>, the Flexdashboard needs to be deployed on a web server. You can easily do this on <a href="https://www.shinyapps.io/">shinyapps.io</a>, you need to have an account for deployment and you can have five apps with the free version. Deploying an Rmd file is similar and as easy as deploying a Shiny app.</p><p>You can deploy the app on your own server or with a cloud service as AWS. I recommend deploying the app within a<strong> </strong>Docker container. Learn why and how you should do this in part two of this series, <a href="https://medium.com/analytics-vidhya/deploying-a-shiny-flexdashboard-with-docker-cca338a10d12"><strong>Deploying a Shiny Flexdashboard with Docker</strong></a><strong>.</strong></p><h4>Update: Improving render time of the Flexdashboard</h4><p>You can now significantly improve the reaction time of the Flexdashboard if you change runtime: shiny to runtime: shiny_prerendered . On default with this option, every code chunk gets rendered once when the Rmd file is rendered. You should set knitr chunk option context=&quot;server”to specify code which comprises the reactive part of your app that executes depending on user interaction. Context set to “data” or “setup” allows for performant sharing of objects between render and server contexts. You could also set a chunk option cache=TRUE for caching pre-computed results and set invalidation conditions. For more information, see <a href="https://rmarkdown.rstudio.com/authoring_shiny_prerendered.html">https://rmarkdown.rstudio.com/authoring_shiny_prerendered.html</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e66aaafac1f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/shiny-dashboards-with-flexdashboard-e66aaafac1f2">Shiny Dashboards with Flexdashboard</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>