Creating new data with max values for each subject

By Abhijit

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

We have a data set dat with multiple observations per subject. We want to create a subset of this data such that each subject (with ID giving the unique identifier for the subject) contributes the observation where the variable X takes it’s maximum value for that subject.

An R solution

Using the excellent R package dplyr, we can do this using windowing functions included in dplyr. The following solution is available on StackOverflow, by junkka, and gets around the real possibility that multiple observations might have the same maximum value of X by choosing one of them.

library(dplyr)
dat_max <- dat %>% group_by(ID) %>% filter(row_number(X)==n())

To be a bit more explicit, row_number is a wrapper around rank, using the option ties.method=“first”. So you can use the rank function explicitly here as well.

A solution using the plyr package might be

library(plyr)
dat_max <- ddply(dat, .(ID), function(u) u[rank(u$X, ties.method='first')==nrow(u),])

A Python solution

In Python, the excellent pandas package allows us to do similar operations. The following example is from this thread on StackOverflow.

import pandas as pd
df = DataFrame({'Sp':[‘a','b‘,'c','d‘,'e','f'], ‘Mt':[‘s1', ‘s1', ‘s2','s2‘,'s2','s3'], ‘Value':[1,2,3,4,5,6], ‘count':[3,2,5,10,10,6]})
df.iloc[df.groupby([‘Mt']).apply(lambda x: x[‘count'].idxmax())]

You could also do (from the same thread)

df.sort(‘count', ascending=False).groupby(‘Mt', as_index=False).first()

but it is about 50% slower.

To leave a comment for the author, please follow the link and comment on his blog: Stat Bandit » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: 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

ASA Statistical Graphics Student Paper Competition

By David Smith

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

If you’re a current graduate or undergraduate student and have a knack for data visualization, why not submit a paper to the 2014 ASA Statistical Graphics Student Paper Competition? Many of the past winners used R to create interesting displays of data, or created a new package for R (general statistical computing applications are also eligible). Winners will get free registration and a travel allowance to attend the Joint Statistics Meetings, which in 2015 will be held in Seattle. (You’ll also get to attend the Statistical Computing Mixer at JSM and participate in the famous door prize giveaway!)

To be considered, you’ll need to submit a six-page manuscript by December 14, 2014. I’ve copied the complete details of the announcement below. Good luck!

The Statistical Computing and Statistical Graphics Sections of the ASA are co-sponsoring a student paper competition on the topics of Statistical Computing and Statistical Graphics. Students are encouraged to submit a paper in one of these areas, which might be original methodological research, some novel computing or graphical application in statistics, or any other suitable contribution (for example, a software-related project). The selected winners will present their papers in a topic-contributed session at the 2015 Joint Statistical Meetings. The Sections will pay registration fees for the winners as well as a substantial allowance for transportation to the meetings and lodging.

Anyone who is a student (graduate or undergraduate) on or after September 1, 2014 is eligible to participate. An entry must include an abstract, a six page manuscript (including figures, tables and references), blinded versions of the abstract and manuscript (with no authors and no references that easily lead to identifying the authors), a C.V., and a letter from a faculty member familiar with the student’s work. The applicant must be the first author of the paper. The faculty letter must include a verification of the applicant’s student status and, in the case of joint authorship, should indicate what fraction of the contribution is attributable to the applicant. We prefer that electronic submissions of papers be in Postscript or PDF. All materials must be in English.

Students may submit papers to no more than two sections and may accept only one section’s award. Students must inform both sections applied to when he or she wins and accepts an award, thereby removing the student from the award competition for the second section.

All application materials MUST BE RECEIVED by 5:00 PM EST, Sunday, December 14, 2014 at the address below. They will be reviewed by the Student Paper Competition Award committee of the Statistical Computing and Graphics Sections. The selection criteria used by the committee will include innovation and significance of the contribution as well as the professional quality of the manuscript. Award announcements will be made by January 15th, 2015.

Additional important information on the competition can be accessed on ASA’s “Student Paper Competition/Travel Award to Attend the Joint Statistical Meetings“.

Inquiries and application materials should be emailed or mailed to:

Student Paper Competition
c/o Aarti Munjal
Colorado School of Public Health
University of Colorado Denver
aarti.munjal@ucdenver.edu

ASA Statistical Computing and Statistical Graphics Section: Student Paper Competition 2014

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

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: 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

R and Data Mining – Examples and Case Studies now in Chinese

By Yanchang Zhao

RDataMining book in Chinese

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

My book titled R and Data Mining – Examples and Case Studies now has its Chinese version, translated by researchers at South China University of Technology, and published by China Machine Press in September 2014. It is sold in China only, at a price of RMB 49 Yuan. If you are in China, it is an opportunity to get a copy of the book at a bargain price.

Details of the book is available at http://www.rdatamining.com/books/rdm, and its original English version can be bought from Amazon at http://www.amazon.com/Data-Mining-Examples-Case-Studies/dp/0123969638.

Its first 11 chapters can be downloaded for free at http://www.rdatamining.com/docs, and R code and data for the book are available at http://www.rdatamining.com/books/rdm/code.

To leave a comment for the author, please follow the link and comment on his blog: blog.RDataMining.com.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: 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

Bio7 2.0 for Windows Released!

By » R

detachedviews

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

01.12.2014

A new Windows version of Bio7 is available. Many new features have been added to Bio7 2.0 which is now based on Eclipse 4.4. Highlights are the improved R editor, the R debugging Graphical User Interface (using the standard R debugger), the integrated Java Development Tools (JDT) to create Java simulation models with a powerful Java editor and the embedded JavaFX SceneBuilder to create embeddable GUI’s on the fly.

Here an overview of the new features:

R

  • Updated R to Version 3.1.2
  • Updated Rserve to version 1.7.3
  • Rserve is now started by default within a R process in a pseudo-terminal in Bio7.
  • The R pseudo-terminal can also be started without Rserve.
  • If started only in the native pseudo-terminal some Rserve functions are not available (e.g. the plots will be displayed in the default R graphic device and not in ImageJ!)
  • The R terminal and Rserve are now sharing the same process.
  • If you switch from Rserve to the R native pseudo-terminal all R Objects will be preserved and vice versa (same process).
  • Implemented a debugging GUI interface for the R debugger visible if a breakpoint in the editor has been set.
  • Added two special debug views to the R perspective.

Video:

  • If a debugging process is started Rserve automatically switches to the native connection.
  • Added an interrupt action to the R-Shell and the R console to interrupt an R evaluation (Strg+c in the console).
  • Added console actions to kill a native process and to kill a native R (Rterm) process if necessary.
  • Created a new single preferences page for the plot setting .

R Editor

  • Integrated an ANTLR R parser for the R editor.
  • Created an editor outline from parsed R scripts.
  • Added a format action (using “formatR” package if installed).
  • Extended the code completions for the R editor.
  • Syntactical errors are now indicated in the editor.
  • Implemented code folding for functions.
  • Implemented hoover actions for the editor (R help for e.g. a function).
  • Improved the recognition of numbers in the R editor.
  • Implemented a marker for matching brackets.
  • Implemented a function to mark reoccuring words in the editor.

Video:

ImageJ and R

  • Added a new action to transfer the values of the ImageJ “Results Table” to R.
  • Improved the Particles action. Now the Particle measurements are transferred from the “Results Table” to R which means that now all values from a stack can be transferred, too.
  • Added a new action to transfer all stack images of an opened stack (also from a nearly non memory consuming virtual stack) to R.
  • A new option is available to convert the stack images to a RasterStack (if the “raster” package is installed).
  • With this action it is also possible to transfer R,G,B values from all slices (images) of a stack, too.
  • Improved the ImageJ image to R API to create matrices from transferred image values.
  • Created an new API method to transfer particle analysis values programmatically.

ImageJ

  • Improved the display. The default image layout now works better after a resize event.
  • ImageJ tabs can now be detached like an image window (see below).
  • Added some improvements for external ImageJ plugins.
  • Updated ImageJ to the latest version.
  • Added more image examples from the ImageJ website.
  • The size of the “Image-Methods” view and the ImageJ toolbar dialog can be adjusted in the Bio7 preferences.

Table

  • Improved the table editing in the “Table” view of Bio7. If you now edit a value and press the return key automatically the next cell is selected for editing (arrow keys for left and right, Tab key for selecting the upper cell).
  • Now the table scales if you paste values or if you transfer vector values from R.
  • The scrollbars now follow the location of the next edited cell.
  • The sheet tabs handle is now located at the bottom of a sheet.
  • The speed of the table component has been improved.

Video:

Java

Video:

  • Embedded the SceneBuilder panels as Bio7 views.
  • Created several new Java wizards to create Bio7 projects, JavaFX projects, etc. in Bio7. They are creating a Bio7 JDT project with all necessary Bio7 classpath libraries. In addition a wizard for a WindowsBuilder project is available, too.
  • Bio7 is now compatible with the most Eclipse plugins which can be installed with the Update Manager of Bio7 (see “General” section below).
  • Improved the compilation which now can detect main classes organized in Java packages.
  • Added a new action to fix the JDT classpath (also invoked if a Bio7 JDT project gets imported). This is necessary to recalculate the JDT library paths for a local Bio7 installation.
  • Hid unnecessary GUI elements from JDT.
  • Updated all scientific and custom Bio7 libraries.
  • Integrated two new SWT libraries to create scientific components and components in general (Nebula visalization – see below, Opal).

  • The Eclipse jobs API can now be used from within Bio7.
  • Ported all Java examples to JDT projects and reorganized the examples.

WorldWind

  • Updated WorldWind to version 2.0.
  • Added an option to select the ImageJ image tab for WorldWind (nice if you want to render a film with ImageJ images).
  • An RGB image can now have transparent alpha values (RGBA) which appear translucent if rendered on the globe.

HTML Editor

  • Added some actions to the editor toolbar to add Knitr templates, links and images.

General

  • It is now possible to install most of the available Eclipse plugins with the update manager of Bio7 (see below – Bio7 with WindowsBuilder installed).

windowbuilder

  • Reorganized the Bio7 preferences for a better usability.
  • Created a new CSS theme for Bio7 (Eclipse Themes plugin for a custom theme can be installed, too)
  • Addded a LaTex editor (Texlipse) to Bio7 for the use with KnitR and Sweave.
  • Added toolbar actions to start the native consoles easier (R, OS Terminal, Python).
  • If you switch from one console to another the process won’t be killed and you can resume a native session (R, Python, OS Terminal).
  • Improved the layout of the “Control” view.
  • Many Eclipse improvements like a split editor action are available by default (Bio7 is based on Eclipse 4.4)
  • Many bugfixes and other improvements.

This release can be downloaded from the Bio7 website:

http://bio7.org

Documentation and videos tutorials can be found here:

Documentation (1.7.1)

YouTube Videos

To leave a comment for the author, please follow the link and comment on his blog: » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: 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

Eight Christmas Gift Ideas for the Statistically Interested

By Rasmus Bååth

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

Christmas is soon upon us and here are some gift ideas for your statistically inclined friends (or perhaps for you to put on your own wish list). If you have other suggestions please leave a comment! 🙂

1. Games of probability

A recently released game where probability takes the main role is Pairs, an easy going press-your-luck game that can be played in 10 minutes. It uses a custom “triangular” deck of cards (1×1, 2×2, 3×3, …, 10×10) and is a lot of fun to play, highly recommended!

Another good gift would be a pound of assorted dice together with the seminal Dice Games Properly Explained by Reiner Knizia. While perhaps not a game, a cool gift to someone that already has a pound of dice would be a set of Non transitive Grime dice.

2. Statistically themed mugs & t-shirts

A search for statistics and mugs or statistics and t-shirts results in a lot of good gifts, for example this t-test mug:

You could also support your favorite MCMC software by buying a STAN themed mug from their shop or why not come up with a custom layout yourself? (I’ve used Vistaprint before and those mugs turned out decent and cheap.)

3. Old school calculation tools

R, Python and Julia are great tools that are perhaps becoming a bit too mainstream for the self-conscious data science hipster. Why not then give the joy of some retro calculation? Slide rulers are amazingly cool and while I don’t know if new are made they can be gotten cheap on ebay. The same goes for vintage pocket calculators (make sure to get one where the digits are in bright green or red). There is also the 50s book with the self describing title A Million Random Digits. (Don’t miss the hilarious reviews on Amazon!)

4. XKCD stuff

The XKCD web comic by Randall Munroe often touches upon statistical issues and while his recent book What If?: Serious Scientific Answers to Absurd Hypothetical Questions is not statistical per see, it contains heaps of amusing back-of-the-envelope calculations. You can also get signed prints of some of the comics, for example of #231 “Cat Proximity”:

5. Comic books teaching statistics

I love comic books teaching statistics (which I’ve written about earlier) and my two favorites are The Cartoon Guide to Statistics by Larry Gonick and Woollcott Smith and The Manga Guide to Statistics by Shin Takahashi. Both are great in their own ways and are enjoyable both if you are a statistics padawan or already a master of the dark arts.

6. Distribution plushies from NausicaaDistribution

NausicaaDistribution sells cool stuff such as a Standard Normal Distribution Plushie, an Evil Cauchy Distribution Plushie and a lot more distributions of different shapes and alignments.

You can also buy a My First Number Sets Wood Puzzle for the budding number theoretician or Famous Statistician Embroidered Coasters to save the sofa table from the eggnog.

7. Statistically themed popular science books

Here are some good popular science books that deals with different aspects of statistics and that anybody can enjoy:

8. Serious statistical science books

Here are some slightly more serious books that I have enjoyed:

To leave a comment for the author, please follow the link and comment on his blog: Publishable Stuff.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: 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

magrittr 1.5

By hadleywickham

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

(Posted on behalf of Stefan Milton Bache)

Sometimes it’s the small things that make a big difference. For me, the introduction of our awkward looking friend, %>%, was one such little thing. I’d never suspected that it would have such an impact on the way quite a few people think and write R (including my own), or that pies would be baked (see here) and t-shirts printed (e.g. here) in honor of the successful three-char-long and slightly overweight operator. Of course a big part of the success is the very fruitful relationship with dplyr and its powerful verbs.

Quite some time went by without any changes to the CRAN version of magrittr. But many ideas have been evaluated and tested, and now we are happy to finally bring an update which brings both some optimization and a few nifty features — we hope that we have managed to strike a balance between simplicity and usefulness and that you will benefit from this update. You can install it now with:

install.packages("magrittr")

The underlying evaluation model is more coherent in this release; this makes the new features more natural extensions and improves performance somewhat. Below I’ll recap some of the important new features, which include functional sequences, a few specialized supplementary operators and better lambda syntax.

Functional sequences

The basic (pseudo) usage of the pipe operator goes something like this:

awesome_data <-
  raw_interesting_data %>%
  transform(somehow) %>%
  filter(the_good_parts) %>%
  finalize

This statement has three parts: an input, an output, and a sequence transformations. That’s suprisingly close to the definition of a function, so in magrittr is really just a convenient way of of defining and applying a function.
A new really useful feature of magrittr 1.5 makes that explicit: you can use %>% to not only produce values but also to produce functions (or functional sequences)! It’s really all the same, except sometimes the function is applied instantly and produces a result, and sometimes it is not, in which case the function itself is returned. In this case, there is no initial value, so we replace that with the dot placeholder. Here is how:

mae <- . %>% abs %>% mean(na.rm = TRUE)
mae(rnorm(10))
#> [1] 0.5605

That’s equivalent to:

mae <- function(x) {
  mean(abs(x), na.rm = TRUE)
}

Even for a short function, this is more compact, and is easier to read as it is defined linearly from left to right.
There are some really cool use cases for this: functionals! Consider how clean it is to pass a function to lapply or aggregate!

info <-
  files %>%
  lapply(. %>% read_file %>% extract(the_goodies))

Functions made this way can be indexed with [ to get a new function containing only a subset of the steps.

Lambda expressions

The new version makes it clearer that each step is really just a single-statement body of a unary function. What if we need a little more than one command to make a satisfactory “step” in a chain? Before, one might either define a function outside the chain, or even anonymously inside the chain, enclosing the entire definition in parentheses. Now extending that one command is like extending a standard one-command function: enclose whatever you’d like in braces, and that’s it:

value %>%
  foo %>% {
    x <- bar(.)
    y <- baz(.)
    x * y
  } %>%
  and_whatever

As usual, the name of the argument to that unary function is ..

Nested function calls

In this release the dot (.) will work also in nested function calls on the right-hand side, e.g.:

1:5 %>% 
  paste(letters[.])
#> [1] "1 a" "2 b" "3 c" "4 d" "5 e"

When you use . inside a function call, it’s used in addition to, not instead of, . at the top-level. For example, the previous command is equivalent to:

1:5 %>% 
  paste(., letters[.])
#> [1] "1 a" "2 b" "3 c" "4 d" "5 e"

If you don’t want this behaviour, wrap the function call in {:

1:5 %>% {
  paste(letters[.])
}
#> [1] "a" "b" "c" "d" "e"

A few of %>%‘s friends

We also introduce a few operators. These are supplementary operators that just make some situations more comfortable.
The tee operator, %T>%, enables temporary branching in a pipeline to apply a few side-effect commands to the current value, like plotting or logging, and is inspired by the Unix tee command. The only difference to %>% is that %T>% returns the left-hand side rather than the result of applying the right-hand side:

value %>%
  transform %T>%
  plot %>%
  transform(even_more)

This is a shortcut for:

value %>%
  transform %>%
  { plot(.); . } %>%
  transform(even_more)

because plot() doesn’t normally return anything that can be piped along!
The exposition operator, %$%, is a wrapper around with(),
which makes it easy to refer to the variables inside a data frame:

mtcars %$%
  plot(mpg, wt)

Finally, we also have %%, the compound assignment pipe operator. This must be the first operator in the chain, and it will assign the result of the pipeline to the left-hand side name or expression. It’s purpose is to shorten expressions like this:

data$some_variable <-
  data$some_variable %>%
  transform

and turn them into something like this:

data$some_variable %<>%
  transform

Even a small example like x %% sort has its appeal!
In summary there is a few new things to get to know; but magrittr is like it always was. Just a little coolr!

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

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: 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

Romain Francois at MilanoR meeting

By MilanoR

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

Romain Francois is a 32-years old R developer and consultant. He defines himself a “Professional R Enthusiast” and r-enthusiasts.com is his website. He co-authored several R packages, such as dplyr and Rcpp.

Romain Francois writes a world famous blog about R and the R Graph Gallery, that showcases hundreds of examples of data visualization with R.

I am honored to announce that Romain Francois is the special guest of the next MilanoR Meeting.

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

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: 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

Interview with SERATRON – Lego EV3 robot driven by R

By smarterpoland

SERVIIb

(This article was first published on SmarterPoland » PISA in English, and kindly contributed to R-bloggers)

Next meeting of Warsaw R Enthusiasts (SER = Spotkania Entuzjastów R) will take place on December 8. We are going to start with Roger Bivand talk about spatial statitics (R Foundation / NHH, author of many R packages). The second talk, by Bartosz Meglicki (IPI PAN), will introduce the SERATRON – fusion of R and Lego Mindstorms.

Below we publish an exclusive SER interview with SERATRON (we are sorry but SERATRON is a naughty one):

SER: Hi, could you introduce yourself?
SERATRON: I am a robot coded in pure R with ev3dev.R bindings. The bindings run on ev3dev linux distribution. The operating system runs on Lego EV3 hardware. We are all under heavy development.

SER: Tell us more about the R part.
SERATRON: I am running RServe server. PCs can communicate with me using RSclient. They do all the heavy computations for me, I can’t be bothered (I have no FPU, can you imagine?!?). Those PCs think they can command me…

SER: Why do you have two servo motors?
SERATRON: So that I can move, you silly!

SER: Hmm, why do you have an infrared sensor?
SERATRON: So that I can avoid obstacles and I will not fall from height. Why do you have eyes donkey?

SER: Errrrrr, what are your touch sensors for?
SERATRON: They also prevent me from falling from height. If I don’t feel the surface below me I am not going to move. Would you?

SER: Ok, last question you naughty robot! What is your gyroscope and accelerometer for?
SERATRON: Can’t you count? It’s not one question but two. I use gyro to know my heading direction. No dumbass, not for balancing, I don’t use it in this axis. I don’t use accelerometer now but I could use tilt input as a third level protection from falling. I could also use it to detect collisions with other objects but I have other means.

SER: It was a pleasure to meet you (coughs), thank you.
SERATRON: I hope I will be finished for SER VII – 08.12.2014!

To leave a comment for the author, please follow the link and comment on his blog: SmarterPoland » PISA in English.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: 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

Turn R (Shiny) Scripts Into Double-clickable OS X Applications With One Line of Code

By Bob Rudis (@hrbrmstr)

Shiny Snowfall.zip

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

I was playing with some non-security-oriented R+Shiny code the other day, and thought that Shiny apps would be even more useful if they were double-clickable applications that you could “just run”—provided R was installed on the target system—vs have to cut/paste code into R. Now, I know it’s not hard to enter:

shiny::runGist('95ec24c1b0cb433a76a5', launch.browser=TRUE)

at an R console, but I’ll wager many developers have users that would still appreciate a double-clickable icon. Since I’m running OS X Yosemite on some of my development machines, I thought this would be a good reason to try out Apple’s new Javascript for Applications (JXA) since I am loath to work in regular AppleScript.

If you fire up Apple’s Script Editor, you can choose which language your script is in from the popup on the script window:

With JXA, all you need is one line of code to run a Shiny gist in R:

Application("R").cmd("shiny::runGist('95ec24c1b0cb433a76a5', launch.browser=TRUE)")

If you like/prefer “pure” AppleScript or are on an older version of OS X you still only need four lines of code:

tell application "R"
  activate
    cmd "shiny::runGist('95ec24c1b0cb433a76a5', launch.browser=TRUE)"
end tell

Save the script as an application and your users will be greeted with your Shiny app in their default browser.

Caveat Scripter

When an application is created this way, it quits immediately after launching R.app and then the R.app window is left open (showing all the R console output from the script). I personally think this is A Very Good Thing, but some folks may not, so you can miniaturize it upon startup via:

R = Application("R")
R.windows[0].miniaturized = true
R.cmd("shiny::runGist('95ec24c1b0cb433a76a5', launch.browser=TRUE)")

or

tell application "R"
  activate
    set miniaturized of window 1 to true
    cmd "shiny::runGist('95ec24c1b0cb433a76a5', launch.browser=TRUE)"
end tell

Users will still need to quit out of R, but you could also add a Shiny actionButton to your app that does a quit(save="no", runLast=FALSE) on submit (example code in this gist) to make it feel like a “real” application.

This all assumes & relies on the fact that the shiny package is already installed on your systems. To ensure any application-dependent packages are installed without forcing the users to manually install them, you can use something like this:

pkg <- c("shiny", "zipcode", "pbapply", "data.table", "dplyr", 
         "ggplot2", "grid", "gridExtra", "stringi", "magrittr")
new.pkg <- pkg[!(pkg %in% installed.packages())]
if (length(new.pkg)) {
  install.packages(new.pkg)
}

at the top of server.R to ensure they are available to your application (note that said hack assumes a CRAN mirror is set).

Finally, for maximum compatibility, you’ll need to use the pure AppleScript version instead of the JXA version unless all your users are on Yosemite or higher.

Example Shiny Snowfall App

If you’re on OS X and have R and the shiny package installed, you can try out the sample “Shiny Snowfall”” app by downloading and unzipping this file (you may need to right/option-click->Save As):

and then running the “Shiny Snowfall” app. (NOTE: You need to have your Security & Privacy settings set to “Allow apps downloaded from ‘Mac App Store and identified developers” to run the application or option/right-click “open” on the app icon”)

The icon used is from Adam Whitcroft’s (@adamwhitcroft) Climacons collection.

To leave a comment for the author, please follow the link and comment on his blog: Data Driven Security.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: 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

Book Review: R Object-oriented Programming

By Arnold Salvacion

(This article was first published on Data Analysis and Visualization in R, and kindly contributed to R-bloggers)

Recently, Packt Publishing publish the book R Object-oriented Programming. The eleven chapter book covers from basic data types in R to a more advanced method such as simulation and writing functions. Different data types (i.e. integer, character, factor) are discussed in-depth in the book as well as numeric and string operations. The good thing with it is that it walks the reader from simple to complicated topic making it easier to learn the language. There are two chapters dedicated in discussing about S3 and S4 classes which are not commonly found published books about R. The last two chapters of the book are dedicated case studies wherein the reader can apply all the learnings from previous chapter. A very good book for beginners and basic users who want to advance their skill and explore the full potential of R as a programming language. Good book to have!

To leave a comment for the author, please follow the link and comment on his blog: Data Analysis and Visualization in R.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: 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