Working efficiently with R – faster to the data product

By eoda GmbH

[R] Kenntnis-Tage 2016 | 2.11-3.11 | Kassel - Germany

(This article was first published on eoda english R news, and kindly contributed to R-bloggers)

Speaker of the [R] Kenntnis-Tage 2016: Julian Gimbel | Lufthansa Industry Solutions

Julian Gimbel works as a data scientist at Lufthansa Industry Solutions. The company supports customers in digitalizing and automating their processes in order to increase their turnover and efficiency while simultaneously reducing their costs.

[R] Kenntnis-Tage 2016 | 2.11-3.11 | Kassel – Germany

In his guest lecture working efficiently with R – faster to the data product, Julian Gimbel will show the comprehensive possibilities to turn analysis results into a data product using visualizing technologies such as Slidify or Shiny. In this way, the laborious preparation of the results for the management can be integrated into the workflow. Based on a classic example from the airline industry, i.e. a forecast of the arrival punctuality of an aircraft, it will be demonstrated how development cycles can be accelerated with a fully integrated programming environment. With R Studio and the package Shiny for interactive graphical user interfaces, a complete development environment for R applications will be presented.

On http://www.eoda.de/de/R-Kenntnis-Tage.html you will find the agenda and further information as well as the registration form for the [R] Kenntnis-Tage 2016.

To leave a comment for the author, please follow the link and comment on their blog: eoda english R news.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more…

Source:: R News

10 featured R jobs from around the world (2016-08-30)

By Tal Galili

r_jobs

Here are the new R Jobs for 2016-08-30.

To post your R job on the next post

Just visit this link and post a new R job to the R community. You can either post a job for free (which works great), or pay $50 to have your job featured (and get extra exposure).

Current R jobs

Job seekers: please follow the links below to learn more and apply for your R job of interest:

Featured Jobs

  1. Full-Time
    Algorithm Developer @ Toronto
    Crescendo Technology Ltd – Posted by Crescendo
    Toronto
    Ontario, Canada
    23 Aug2016
  2. Full-Time
    Enterprise Advocate for RStudio
    RStudio Inc. – Posted by jclemens1
    Anywhere
    23 Aug2016
  3. Full-Time
    Assistant/Associate Professor in Innovative Qualitative Methodologies – 003539-2016 Cluster Hire
    Purdue University – Posted by Purdueclusterhiresearch
    West Lafayette
    Indiana, United States
    11 Aug2016
  4. Full-Time
    Assistant/Associate Professor in Innovative Quantitative Methodologies – 003538-2016 Cluster Hire
    Purdue University – Posted by Purdueclusterhiresearch
    West Lafayette
    Indiana, United States
    11 Aug2016
  5. Part-Time
    Shiny developer
    ironAPI – Posted by Babak
    Wien
    Wien, Austria
    8 Aug2016
  6. Full-Time
    Data Science Faculty (Assistant/Associate Professor, Tenure Track)
    Saint Louis University – Posted by armbrees
    St. Louis
    Missouri, United States
    7 Aug2016
  7. Full-Time
    Data Scientist / Bioinformatician / Statistician at University of California
    UCSF – Posted by clif.duhn
    San Francisco
    California, United States
    2 Aug2016
  8. Freelance
    Big Data in Digital Health (5-10 hours per week)
    MedStar Intitute for Innovation – Posted by Praxiteles
    Anywhere
    1 Aug2016
  9. Full-Time
    Data Scientist – Analytics
    Booking.com – Posted by work_at_booking
    Anywhere
    1 Aug2016
  10. Full-Time
    Economic Analyst
    Thumbtack – Posted by Thumbtack
    Anywhere
    26 Jul2016

More New Jobs

  1. Full-Time
    Algorithm Developer @ Toronto
    Crescendo Technology Ltd – Posted by Crescendo
    Toronto
    Ontario, Canada
    23 Aug2016
  2. Full-Time
    Enterprise Advocate for RStudio
    RStudio Inc. – Posted by jclemens1
    Anywhere
    23 Aug2016
  3. Full-Time
    Statistical Data Analytics Web Analyst @ London
    uSwitch – Posted by jobs@uswitch.com
    London
    England, United Kingdom
    18 Aug2016

In R-users.com you can see all the R jobs that are currently available.

R-users Resumes

R-users also has a resume section which features CVs from over 200 R users. You can submit your resume (as a “job seeker”) or browse the resumes for free.

(you may also look at previous R jobs posts).

Source:: R News

Desktop in the Cloud

By adamleerich

(This article was first published on TeachR, and kindly contributed to R-bloggers)

I just wanted to share the good experience I have had with creating a virtual personal desktop on Paperspace. A few months ago I started researching whether there was anyone out there providing this service. Paperspace came up in the search but their service was not yet available. But, to my surprise, they were available the other night when I needed some extra computing power ASAP. Their souped-up desktop runs with 32 GB of RAM and 8 CPUs. You can pay monthly or by the hour and the rates are pretty reasonable. What is amazing is the speed. I was really impressed today with the download speeds, of all things. I had an entire R development stack set up and ready to go in 30 mins or less (R, RStudio, tools, github, git, Sublime, and on and on). AND, I’ve created a snapshot of the setup so I can spin up a new instance in the future, if I screw something up.

They are still a new company, small enough to still be personal, evidenced by the one-on-one conversation I’ve been having this evening with one of their outreach guys, Paul Kleen (paul AT paperspace DOT com). He’s offered free storage to anyone who emails him in response to this post, all you have to pay is the hourly usage fees. He offered me credits if anyone signs up but I am declining those because I don’t want you to think this is just a sales pitch. I really am impressed with this service and it totally hit the spot in a time of need. Try it out and you will love it.

Oh, and while I was setting this up, I tried to do the same on Azure and burned through $200 of credits before I even got to use the machine. Amazon suspended my account. The other smaller players I didn’t even try — too sketchy looking. Paperspace on the other hand is offering a good service that I can really stand behind.

To leave a comment for the author, please follow the link and comment on their blog: TeachR.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more…

Source:: R News

RProtoBuf 0.4.5: now with protobuf v2 and v3!

By Thinking inside the box

(This article was first published on Thinking inside the box , and kindly contributed to R-bloggers)

A few short weeks after the 0.4.4 release of RProtoBuf, we are happy to announce a new version 0.4.5 which appeared on CRAN earlier today.

RProtoBuf provides R bindings for the Google Protocol Buffers (“Protobuf”) data encoding library used and released by Google, and deployed as a language and operating-system agnostic protocol by numerous projects.

This release brings support to the recently-release ‘version 3′ Protocol Buffers standard, used e.g. by the (very exciting) gRPC project (which was just released as version 1.0). RProtoBuf continues to supportv ‘version 2′ but now also cleanly support ‘version 3′.

Changes in RProtoBuf version 0.4.5 (2016-08-29)

  • Support for version 3 of the Protcol Buffers API

  • Added ‘syntax = “proto2”;’ to all proto files (PR #17)

  • Updated Travis CI script to test against both versions 2 and 3 using custom-built .deb packages of version 3 (PR #16)

  • Improved build system with support for custom CXXFLAGS (Craig Radcliffe in PR #15)

CRANberries also provides a diff to the previous release. The RProtoBuf page has an older package vignette, a ‘quick’ overview vignette, a unit test summary vignette, and the pre-print for the JSS paper. Questions, comments etc should go to the GitHub issue tracker off the GitHub repo.

This post by Dirk Eddelbuettel originated on his Thinking inside the box blog. Please report excessive re-aggregation in third-party for-profit settings.

To leave a comment for the author, please follow the link and comment on their blog: Thinking inside the box .

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more…

Source:: R News

RClimate Script to Assess Local Hot Day Trends

By Kelly

hot_day_trend_ KPHL

(This article was first published on RClimate, and kindly contributed to R-bloggers)

There is ample evidence of global climate change, these are just a few examples (here, here, here).

While global indicators are important to focus attention on the problem and solutions, local data is important to help us understand the situation in our own areas. There are a number of R packages that let users download and analyze weather data to investigate the climate change situation in local geographic areas.

I find the weatherData package an excellent tool for local climate change investigations. AS an example, I downloaded daily weather data for my local airport for the period 1950 – 2015, ran a simple r-script to count and save the number of 90+ days each summer period to a csv file. This hot day trend chart is an example of what R users can do to visualize the changing climate.

This chart shows that the number of 90+ days in Philadelphia has increased in the past 66 years. Prior to 1983 (midpoint of period), only 5 out of 30 years have 30 or more days of 90+ max temperatures. Since 1984, 13 of 36 years had 30 or more days of 90+ max temperatures. 2016 has had 38 days through August 28, making 16 of 37 years with 30 or more 90+ days.

My R script is reproduced below. My R base graphics script could be easily reproduced in ggplot2.

  library(weatherData)
  library(stats)
  airport <- "KPHL"
## user can specify moving average period 
  ma_period <- 10
  ma_legend <- paste(ma_period," year moving avg")  
  
  setwd("F:enter woring directory here ")
 
## Read data from prev downloaded weather data file
  input_file <-  "F:enter input file name.csv"
  df <- read.csv(input_file, as.is=T)
  start_yr <- df[1,1]
  end_yr <- df[nrow(df),1]
  num_yrs <- end_yr -start_yr +1
  my_date <- format(Sys.Date(),"%m/%d/%Y")

## Use plot function to enable saving png as well as console display
 plot_func_1 <- function() {
   par(las=1); par(mar=c(1,4,5,1)); par(oma = c(3,2,2,1)); par(ps=11)
   title_1 <- paste("KPHLnNumber days in year with Max temperaure >= ",90,
            "n in hot weather months of May 1 - August 31n",  start_yr, " through ", end_yr)
  plot(df$year, df$hot_day_count, type="n", lwd=3,
     main=title_1,  cex.main=0.8,   xlab="", ylab = "Number of days",
     ylim <- c(0,60),xlim=c(start_yr, end_yr) ) 
  grid(col = "lightgrey", lty=1) 
  points(df$year, df$hot_day_count, type="h", col="red", lwd=2) 
 
  legend("topleft", c(ma_legend, "No. days max temp >= 90", "Trend Line"), col = c("blue", "red","black"),
         text.col = "black", lty = c(1),pt.cex=c(0),  x.intersp = 0.25, y.intersp = 0.7,
         merge = T, bg = "transparent", bty="n", box.col = "black", cex = 0.7,seg.len=1, lwd=3)
  
## calculate and add 10 year moving average to plot
  ma <- stats::filter(df$hot_day_count, rep(1/ma_period,ma_period),sides=1 )
  my_seq <- seq(start_yr, end_yr)
  ma_df <- data.frame(my_seq, ma)
  names(ma) <- c("yr","ma")
  points(ma_df$my_seq, ma_df$ma, type="l", col="blue",lw=3)  
  abline(lm(hot_day_count ~ year, data = df),col="black")
  mtext("Kelly O'Day - http://RClimate.wordpress.com", side = 1, line = 1, cex=0.7, outer = T, adj = 0)
  mtext(my_date, side = 1, line =1, cex = 0.7, outer = T, adj = 1)
         }  
  out_file <-  paste("hot_day_trend_",airport,".png")  # location for png olot file
  png(file=out_file,width=1290,height=1000, res=200)  
  plot_func_1()  # send plot to png device
  dev.off()  # turn off png device
  plot_func_1()  # plot to console

To leave a comment for the author, please follow the link and comment on their blog: RClimate.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more…

Source:: R News

tibble 1.2.0

By hadleywickham

(This article was first published on RStudio Blog, and kindly contributed to R-bloggers)

We’re proud to announce version 1.2.0 of the tibble package. Tibbles are a modern reimagining of the data frame, keeping what time has shown to be effective, and throwing out what is not. Grab the latest version with:

install.packages("tibble")

This is mostly a maintenance release, with the following major changes:

  • More options for adding individual rows and (new!) columns
  • Improved function names
  • Minor tweaks to the output

There are many other small improvements and bug fixes: please see the release notes for a complete list.

Thanks to Jenny Bryan for add_row() and add_column() improvements and ideas, to William Dunlap for pointing out a bug with tibble’s implementation of all.equal(), to Kevin Wright for pointing out a rare bug with glimpse(), and to all the other contributors. Use the issue tracker to submit bugs or suggest ideas, your contributions are always welcome.

Adding rows and columns

There are now more options for adding individual rows, and columns can be added in a similar way, illustrated with this small tibble:

df <- tibble(x = 1:3, y = 3:1)
df
#> # A tibble: 3 × 2
#>       x     y
#>   <int> <int>
#> 1     1     3
#> 2     2     2
#> 3     3     1

The add_row() function allows control over where the new rows are added. In the following example, the row (4, 0) is added before the second row:

df %>% 
  add_row(x = 4, y = 0, .before = 2)
#> # A tibble: 4 × 2
#>       x     y
#>   <dbl> <dbl>
#> 1     1     3
#> 2     4     0
#> 3     2     2
#> 4     3     1

Adding more than one row is now fully supported, although not recommended in general because it can be a bit hard to read.

df %>% 
  add_row(x = 4:5, y = 0:-1)
#> # A tibble: 5 × 2
#>       x     y
#>   <int> <int>
#> 1     1     3
#> 2     2     2
#> 3     3     1
#> 4     4     0
#> 5     5    -1

Columns can now be added in much the same way with the new add_column() function:

df %>% 
  add_column(z = -1:1, w = 0)
#> # A tibble: 3 × 4
#>       x     y     z     w
#>   <int> <int> <int> <dbl>
#> 1     1     3    -1     0
#> 2     2     2     0     0
#> 3     3     1     1     0

It also supports .before and .after arguments:

df %>% 
  add_column(z = -1:1, .after = 1)
#> # A tibble: 3 × 3
#>       x     z     y
#>   <int> <int> <int>
#> 1     1    -1     3
#> 2     2     0     2
#> 3     3     1     1

df %>%  
  add_column(w = 0:2, .before = "x")
#> # A tibble: 3 × 3
#>       w     x     y
#>   <int> <int> <int>
#> 1     0     1     3
#> 2     1     2     2
#> 3     2     3     1

The add_column() function will never alter your existing data: you can’t overwrite existing columns, and you can’t add new observations.

Function names

frame_data() is now tribble(), which stands for “transposed tibble”. The old name still works, but will be deprecated eventually.

tribble(
  ~x, ~y,
   1, "a",
   2, "z"
)
#> # A tibble: 2 × 2
#>       x     y
#>   <dbl> <chr>
#> 1     1     a
#> 2     2     z

Output tweaks

We’ve tweaked the output again to use the multiply character × instead of x when printing dimensions (this still renders nicely on Windows.) We surround non-semantic column with backticks, and dttm is now used instead of time to distinguish POSIXt and hms (or difftime) values.

The example below shows the new rendering:

tibble(`date and time` = Sys.time(), time = hms::hms(minutes = 3))
#> # A tibble: 1 × 2
#>       `date and time`     time
#>                <dttm>   <time>
#> 1 2016-08-29 16:48:57 00:03:00

Expect the printed output to continue to evolve in next release. Stay tuned for a new function that reconstructs tribble() calls from existing data frames.

To leave a comment for the author, please follow the link and comment on their blog: RStudio Blog.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more…

Source:: R News

Want to learn how to make maps in R?

By Ari Lamstein

bottom

(This article was first published on R – AriLamstein.com, and kindly contributed to R-bloggers)

Once upon a time I wrote an open source package that makes it easy to create choropleth maps in R. I called the package choroplethr.

Then I created a free email course to teach people how to use the software. That course is called Learn to Map Census Data in R, and it is the most popular thing that I’ve ever published.

People who took that course asked me a lot of questions about choroplethr. So I created a separate course for them. That course is called Mapmaking in R with Choroplethr. It sold for $99 and was very popular. Here’s an image from that course

People who took that course wound up having a lot of questions too. In particular, they wanted to learn how to work with shapefiles. So I made a separate course for them: Shapefiles for R Programmers. That course also sold for $99 and was well received. Here’s an image from that course:

Today you can buy both courses for $1 (a $197 savings)

Last week I decided to stop offering the courses for individual sale, and instead make them part of my new membership.

The membership normally costs $49 a month. But to celebrate this change, I have decided to offer a 1 month trial for only $1. This offer ends Thursday, September 1.

Why are you bundling the courses with the membership site?

Because the membership provides a better environment for learning.

In addition to the courses, the membership has a forum where you can ask questions, and bi-monthly live office hours where we can discuss the courses and other questions that you have.

Can I ask other questions in the membership?

Absolutely.

The membership exists to help people create, publish and profit from R projects. Anything related to that theme is fair game.

Will you be creating more courses in the future?

That’s the plan. And they will be added to the membership library. In that sense, the value of the membership will increase over time.

Like before, I will decide the topic for new courses based on feedback from members / people who took previous courses.

How can I learn more?

Click here.

The post Want to learn how to make maps in R? appeared first on AriLamstein.com.

To leave a comment for the author, please follow the link and comment on their blog: R – AriLamstein.com.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more…

Source:: R News

Video series: Introduction to Microsoft R Server

By David Smith

(This article was first published on Revolutions, and kindly contributed to R-bloggers)

Microsoft R Server extends the base R language and Microsoft R Open with big-data capabilities. Specifically, it adds the RevoScaleR package, which creates an out-of-memory “CDF” data structure (so you can process data larger than available RAM), and algorithms that allow you to perform computations on such data using parallel and distributed algorithms. (A limited version of the RevoScaleR package is also included in the free Microsoft R Client.)

If you’d like to get up to speed on the capabilities of Microsoft R Server, my colleague Matt Parker has created a 4-part video series that introduces Microsoft R Server and delves into data ingestion, data management, and predictive modeling. The videos are embedded below, and you can also download the videos for offline viewing from Channel 9.

Part 1: Introduction to Microsoft R Server

Part 2: Data Ingestion

This video covers the eXternal Data Frame (XDF) format, and functions for importing data from files and databases.

Part 3: Data Management

This video covers key functions for the standard data management tasks: creating and modifying variables, sorting, subsetting, deduplication, and merging datasets.

Part 4: Predictive Modeling

This video focuses on functions for exploring and summarizing data, building predictive models, and making predictions.

If you’d like to follow along with the videos on your own PC, you can download Microsoft R Client for free and use all of the functions described in the video.

Channel 9: Microsoft R Server 4-part series

To leave a comment for the author, please follow the link and comment on their blog: Revolutions.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more…

Source:: R News

Make Bland Altman Plots with Marginal Histograms using ggExtra

By dtholmes@mail.ubc.ca

plot of chunk unnamed-chunk-1

(This article was first published on The Lab-R-torian, and kindly contributed to R-bloggers)

The Problem

As you know in Clinical Chemistry, we are not always writing a major paper but sometimes just preparing a short-report to answer a technical question that we’ve encounted at work. For shorter papers, journals often have more stringent rules about how many figures you can submit and even sometimes forbid multipanelled figures. In these situations, we might want to cram a little more into your figure than we might otherwise. In a recent submission, I wanted to produce a difference plot of immunoassay results before and after storage but I also wanted to show the distribution of the results using a histogram–but this would have counted as two separate figures.

However, thanks to some fine work by Dean Attali of UBC Department of Statistics where he works with R-legend Jenny Bryan, it is quite easy to add marginal histograms to a Bland Altman (or any other scatter) plot using the ggExtra package.

How To

Let’s make some fake data for a Bland Altman plot. Let’s pretend that we are measuring the same quantity by immunoassay at baseline and after 1 year of storage at -80 degrees. We’ll add some heteroscedastic error and create some apparent degradation of about 20%:

set.seed(10) #make predictable random data
baseline <- rlnorm(100, 0, 1)
post <- 0.8*baseline + rnorm(100, 0, 0.10*baseline)
plot(baseline,post)
abline(lm(post ~ baseline))
abline(0, 1, col="red", lty = 2)

Or if we plot this in the ggplot() paradigm

library(ggplot2)
my.data <- data.frame(baseline, post)
ggplot(my.data, aes(x=baseline, y=post)) +
    theme_bw() + 
    geom_point(shape=1) +    # Use hollow circles
    geom_smooth(method=lm) +  # Add linear regression line 
    geom_abline(slope = 1, intercept = 0, linetype = 2, colour = "red")

plot of chunk unnamed-chunk-2

Now we will prepare the difference data:

diff <- (post - baseline)
diffp <- (post - baseline)/baseline*100
sd.diff <- sd(diff)
sd.diffp <- sd(diffp)
my.data <- data.frame(baseline, post, diff, diffp)

In standard Bland Altman plots, one plots the difference between methods against the average of the methods, but in this case, the x-axis should be the baseline result, because that is the closest thing we have to the truth.

library(ggExtra)
diffplot <- ggplot(my.data, aes(baseline, diff)) + 
  geom_point(size=2, colour = rgb(0,0,0, alpha = 0.5)) + 
  theme_bw() + 
  geom_hline(yintercept = 0, linetype = 3) +
  geom_hline(yintercept = mean(my.data$diff)) +
  geom_hline(yintercept = mean(my.data$diff) + 2*sd.diff, linetype = 2) +
  geom_hline(yintercept = mean(my.data$diff) - 2*sd.diff, linetype = 2) +
  ylab("Difference pre and post Storage (mg/L)") +
  xlab("Baseline Concentration (mg/L)")

#And now for the magic - we'll use 25 bins
ggMarginal(diffplot, type="histogram", bins = 25)

plot of chunk unnamed-chunk-4

So that is the difference plot for the absolute difference. We can also obviously do the percent difference.

diffplotp <- ggplot(my.data, aes(baseline, diffp)) + 
  geom_point(size=2, colour = rgb(0,0,0, alpha = 0.5)) + 
  theme_bw() + 
  geom_hline(yintercept = 0, linetype = 3) +
  geom_hline(yintercept = mean(my.data$diffp)) +
  geom_hline(yintercept = mean(my.data$diffp) + 2*sd.diffp, linetype = 2) +
  geom_hline(yintercept = mean(my.data$diffp) - 2*sd.diffp, linetype = 2) +
  ylab("Difference pre and post Storage (%)") +
  xlab("Baseline Concentration (mg/L)")


ggMarginal(diffplotp, type="histogram", bins = 25)

plot of chunk unnamed-chunk-5

Kickin’ it Old School

You can also do this in a non-ggplot() paradigm using base plotting utilities as described in this R-bloggers post.

Conclusion

And that, friends, is a way of squishing in a histogram of your sample concentrations into your difference plot which allows you to graphically display your sampling distribution and justify whether you would use parametric or non-parametric statistics to assess the extent of loss of immunoreactivity from storage.

And speaking of scatterplots

“…then the Lord your God will restore your fortunes and have compassion on you and gather you again from all the nations where he scattered you.”
Deut 30:3

To leave a comment for the author, please follow the link and comment on their blog: The Lab-R-torian.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more…

Source:: R News

Shiny tips & tricks for improving your apps and solving common problems

By Dean Attali's R Blog

Demo

(This article was first published on Dean Attali’s R Blog, and kindly contributed to R-bloggers)

This document contains a collection of various Shiny tricks that I commonly use or that I know many people ask about. Each link contains a complete functional Shiny app that demonstrates how to perform a non trivial task in Shiny. The complete up-to-date list of tips, along with all the code, is on GitHub.

Click here to see the most up-to-date list of tips

Since I first learned about Shiny 2 years ago, I was always looking for ways to push Shiny to its limits and I enjoyed finding ways to work around common problems people were having (the harder the problem, the better!). I’ve built many Shiny apps over these 2 years, both for myself and as a contractor for other people/companies, and throughout this time I developed a handy list of Shiny design patterns and tricks, some of which I present here.

This also seems like an appropriate place to mention that I am available for hire, so if you need some help with anything Shiny, feel free to contact me.

Table of contents

Prereq: How to hide/show something in Shiny? How to disable an input? How do I reset an input?

A few very common questions in Shiny are “how do I hide/show something”, “how do I disable an input”, and “how do I reset an input”. Many of the code samples in this document also rely on being able to do these things, so I wanted to start by saying that I will be using the shinyjs package to do all that. (Yes, I know it looks like I’m shamelessly advertising shinyjs by saying this… but it is going to be useful for many concepts here)

Show a spinning “loading” animation while a plot is recalculating

Link to code

When a Shiny plot is recalculating, the plot gets grayed out. This app shows how you can add a spinner wheel on top of the plot while it is recalculating, to make it clear to the user that the plot is reloading. There can be many different ways to achieve a similar result using different combinations of HTML/CSS, this example is just the simplest one I came up with.

Hide a tab

Link to code

This app demonstrates how shinyjs can be used to hide/show a specific tab in a tabsetPanel. In order to use this trick, the tabsetPanel must have an id. Using this id and the value of the specific tab you want to hide/show, you can call shinyjs::hide()/shinyjs::show()/shinyjs::toggle().

Hide/show shinydashboard sidebar programmatically

Link to code

A common question regarding shinydashboard is how to programmatically hide/show the sidebar. This can very easily be done using the shinyjs package, as demonstrated here.

Demo

Loading screen

Link to code

This simple app shows how to add a “Loading…” screen overlaying the main app while the app’s server is initializing. The main idea is to include an overlay element that covers the entire app (using CSS), hide the main app’s UI, and at the end of the server function show the UI and hide the overlay.

Demo

Automatically stop a Shiny app when closing the browser tab

Link to code

When developing a Shiny app and running the app in the browser (as opposed to inside the RStudio Viewer), it can be annoying that when you close the browser window, the app is still running and you need to manually press “Esc” to kill it. By adding a single line to the server code session$onSessionEnded(stopApp), a Shiny app will automatically stop running whenever the browser tab (or any session) is closed.

Close the window (and stop the app) with a button click

Link to code

This simple example shows how you can have a button that, when clicked, will close the current browser tab and stop the running Shiny app (you can choose to do only one of these two actions).

Select input with more breathing room

Link to code

One common CSS question in Shiny is how to make the select input dropdown menu have some more whitespace. It’s actually very easy to do with just two CSS rules, as demonstrated in this example.

Demo

Select input with groupings of options

Link to code

This isn’t really a trick as much as an undocumented feature in Shiny that not many people know about. Usually when people write dropdowns in Shiny, all the options are just provided as one long list. But it is possible to have groups of items, and it’s very easy to do.

Demo

Getting the value of an object in a running Shiny app without access to a debugger

Link to code

Sometimes you may need to know the value of some variable/function call in a Shiny app when you don’t have easy access to debugging tools. For example, suppose you deploy your shiny app on shinyapps.io and it’s running into a weird error there. You’re sure that it’s because one of the packages on the shinyapps.io server is not the version that you expect, but you want to make sure that your suspicion is correct. It’s a bit difficult to debug on shinyapps.io (one thing you could do is try to use the log files), but there’s a quick and easy way to see any value in a Shiny app in real-time.

Pre-populate Shiny inputs when an app loads based on URL parameters

Link to code

This simple app demonstrates how you can fill out certain input fields when a Shiny app loads based on URL parameters.

Demo

Split app code across multiple files (when codebase is large)

Link to code

When creating Shiny apps with a lot of code and a complex UI, it can sometimes get very messy and difficult to maintain your code when it’s all in one file. What you can do instead is have one “main” UI and “main” server and split your UI and server code into multiple files. This can make your code much more manageable and easier to develop when it grows large. You can split the code however you want, but I usually like to split it logically: for example, if my app has 4 tabs then the UI for each tab would be in its own file and the server code for each tab would be in its own file. The example code here shows how to separate the code of an app with two tabs into 2 UI files and 2 server files (one for each tab).

Use a variable from the server in a UI `conditionalPanel()`

Link to code

When using a conditional panel in the UI, the condition is usually an expression that uses an input value. But what happens when you want to use a conditional panel with a more complex condition that is not necessarily directly related to an input field? This example shows how to define an output variable in the server code that you can use in the UI. An alternative approach is to use the show() and hide() functions from the shinyjs package.

Show user a generic error message when a Shiny error occurs in an output

Link to code

When a Shiny output encounters an error, the exact error message will be shown to the user in place of the output. This is generally a good feature because it’s easier to debug when you know the exact error. But sometimes this is undesireable if you want to keep the specifics of what happened unknown to the user, and you prefer to just show the user a generic “Some error occurred; please contact us” message. This may sound counter intuitive, but you can actually do this with a tiny bit of CSS, as this example shows.

Fix filenames of files uploaded via fileInput()

Link to code

When selecting files using a fileInput(), the filenames of the selected files are not retained. This is not usually a problem because usually you only care about the contents of a file and not its name. But sometimes you may actually need to know the original name of each selected file. This example shows how to write a simple function fixUploadedFilesNames() to rename uploaded files back to their original names.

Shiny app with sequence of pages

Link to code

This app demonstrates how to write a Shiny app that has a sequence of different pages, where the user can navigate to the next/previous page. This can be useful in many scenarios that involve a multi-step process. This behaviour can also be achieved by simply using tabs, but when using tabs the user can freely move from any tab to any other tab, while this approach restricts the user to only move to the previous/next step, and can also control when the user can move on to the next page.

Demo

Toggle a UI element (alternate between show/hide) with a button

Link to code

Sometimes you want to toggle a section of the UI every time a button is clicked. This app shows how to achieve very basic toggle functionality using conditionalPanel(). If you want anything more advanced, you can use the toggle() function from the shinyjs package.

Send a message from R to JavaScript

Link to code

While Shiny is very powerful, there are many things that cannot be achieved in R and must be done in JavaScript. When including JavaScript code in a Shiny app, you sometimes need to send a message or a value from R to the JavaScript layer. This example how this is done.

Send a message from JavaScript to R

Link to code

In some shiny applications you may want to send a value from JavaScript to the R server. This can be useful in a variety of applications, for example if you want to capture a mouse click or a keyboard press of the user and tell R about it. This example shows how this is done.

Send a message from JavaScript to R – force repetitive messages to get sent

Link to code

When you send a message from JS to R with the exact same value multiple times in a row, only the first time actually gets sent to Shiny. This can often be problematic, and this example shows a fairly simple workaround.

Press the Enter key to simulate a button press

Link to code

This is a simple app with a tiny bit of JavaScript that shows you how to cause an Enter key press inside an input to trigger a click on a button.

Serve files (images/text files/etc) instead of webpages from a Shiny app

Link to code

It is possible to serve an image or another file directly from your Shiny app instead of a webpage. The method shown here is a simple proof-of-concept of how to achieve this functionality. It also supports passing GET parameters to the file-generating logic so that the file can be parameterized.

Demo

Update multiple Shiny inputs without knowing input type

Link to code

Shiny allows you to update an input element only if you know the type of input. Furthermore, Shiny only allows you to update input elements one by one. This Shiny app shows how you can update an input only using its ID and without knowing its type, and how to update multiple inputs together.

“Busy…” / “Done!” / “Error” feedback after pressing a button

Link to code

When the user clicks on a button, it usually results in some R code being run. Sometimes the resulting code is short and quick and the user doesn’t even notice any delay, but sometimes the button click initialiates some long process or computation that can take more than 1 second to complete. In those cases, it might be a bit confusing to the user if there is no immediate feedback notifying that the action is being performed. For example, if the user clicked a button to load data from a database and it takes 3 seconds to connect to the database, it can be useful to show a “Connecting…” and then a “Done!” (or “Error”) message, instead of just letting the user wait without seeing any message. Of course when the wait time is only 2-3 seconds it’s not a big deal, but you can imagine that for a 20-second process, the user might think that something went wrong if there is no feedback. This example shows how to add some immediate feedback to the user after a button is clicked, including disabling/enabling the button and showing a success/error message when appropriate.

Demo

Simple AJAX system for Shiny apps (JS -> R -> JS communication)

Link to code

Sometimes it’s useful to be able to call an R function from JavaScript and use the return value from R back in JavaScript. This sort of communication is usually done with AJAX in JavaScript. This app shows how to implement a simple and ultra lightweight AJAX-like system in Shiny, to be able to call functions in R.

Navigation in a Shiny app (forward/backwards in history)

Link to code

Sometimes it’s nice to be able to support navigation within a Shiny app, especially when there are multiple tabs or some other form of “multiple pages” in a Shiny app. Since Shiny apps are a single page, the browser nagivation buttons (previous/next page) don’t work when “navigating” within a Shiny app. You also can’t bookmark a certain “page” in a Shiny app – every time you go to an app, you will be shown the initial state of the app. This app shows how to implement basic navigation in Shiny apps.

Demo

Sharing images on Facebook

Link to code

There are two ways to share images on Facebook: either using an image URL and a popup dialog, or by programmatically supplying the Facebook API with a base64 encoded image. This example shows both.

Facebook login through JavaScript in Shiny

Link to code

This app shows how you can use the AJAX-like system in Shiny to authorize a user using Facebook’s JavaScript library and pass the user’s information to R for processing.

Multiple scrollspy on same page – basic

Link to code

The Bootstrap scrollspy plugin does not support multiple scrollspy objects per page. This Shiny app demonstrates how to support scrollspy on multiple tabs by having one common scrollspy control that gets updated via JavaScript whenever a tab is changed to reflect the contents of the new tab.

Multiple scrollspy on same page – advanced

Link to code

The Bootstrap scrollspy plugin does not support multiple scrollspy objects per page.
This Shiny app demonstrates how to support scrollspy on multiple tabs by allowing each tab to have its own independent scrollspy control and using JavaScript to ensure only the scrollspy on the current tab is activated.

To leave a comment for the author, please follow the link and comment on their blog: Dean Attali’s R Blog.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more…

Source:: R News