You are currently browsing the category archive for the ‘Packages’ category.

We are excited to announce that a new package leaflet has been released on CRAN. The R package leaflet is an interface to the JavaScript library Leaflet to create interactive web maps. It was developed on top of the htmlwidgets framework, which means the maps can be rendered in R Markdown (v2) documents, Shiny apps, and RStudio IDE / the R console. Please see http://rstudio.github.io/leaflet for the full documentation. To install the package, run

install.packages('leaflet')

We quietly introduced this package in December when we announced htmlwidgets, but in the months since then we’ve added a lot of new features and launched a new set of documentation. If you haven’t looked at leaflet lately, now is a great time to get reacquainted!

The Map Widget

The basic usage of this package is that you create a map widget using the leaflet() function, and add layers to the map using the layer functions such as addTiles(), addMarkers(), and so on. Adding layers can be done through the pipe operator %>% from magrittr (you are not required to use %>%, though):

library(leaflet)

m <- leaflet() %>%
  addTiles() %>%  # Add default OpenStreetMap map tiles
  addMarkers(lng=174.768, lat=-36.852,
    popup="The birthplace of R")
m  # Print the map

leaflet-basic

There are a variety of layers that you can add to a map widget, including:

  • Map tiles
  • Markers / Circle Markers
  • Polygons / Rectangles
  • Lines
  • Popups
  • GeoJSON / TopoJSON
  • Raster Images
  • Color Legends
  • Layer Groups and Layer Control

There are a sets of methods to manipulate the attributes of a map, such as setView() and fitBounds(), etc. You can find the details from the help page ?setView.

Read the rest of this entry »

We are happy to announce a new package DT is available on CRAN now. DT is an interface to the JavaScript library DataTables based on the htmlwidgets framework, to present rectangular R data objects (such as data frames and matrices) as HTML tables. You can filter, search, and sort the data in the table. See http://rstudio.github.io/DT/ for the full documentation and examples of this package. To install the package, run

install.packages('DT')
# run DT::datatable(iris) to see a "hello world" example

DataTables

The main function in this package is datatable(), which returns a table widget that can be rendered in R Markdown documents, Shiny apps, and the R console. It is easy to customize the style (cell borders, row striping, and row highlighting, etc), theme (default or Bootstrap), row/column names, table caption, and so on.

Read the rest of this entry »

We’re pleased to announce d3heatmap, our new package for generating interactive heat maps using d3.js and htmlwidgets. Tal Galili, author of dendextend, collaborated with us on this package.

d3heatmap is designed to have a familiar feature set and API for anyone who has used heatmap or heatmap.2 to create static heatmaps. You can specify dendrogram, clustering, and scaling options in the same way.

d3heatmap includes the following features:

  • Shows the row/column/value under the mouse cursor
  • Click row/column labels to highlight
  • Drag a rectangle over the image to zoom in
  • Works from the R console, in RStudio, with R Markdown, and with Shiny

Installation

install.packages("d3heatmap")

Examples

Here’s a very simple example (source: flowingdata):

library(d3heatmap)
url <- "http://datasets.flowingdata.com/ppg2008.csv"
nba_players <- read.csv(url, row.names = 1)
d3heatmap(nba_players, scale = "column")

d3heatmap

You can easily customize the colors using the colors parameter. This can take an RColorBrewer palette name, a vector of colors, or a function that takes (potentially scaled) data points as input and returns colors.

Read the rest of this entry »

Shiny 0.12 has been released to CRAN!

Compared to version 0.11.1, the major changes are:

  • Interactive plots with base graphics and ggplot2
  • Switch from RJSONIO to jsonlite

For a full list of changes and bugfixes in this version, see the NEWS file.

To install the new version of Shiny, run:

install.packages(c("shiny", "htmlwidgets"))

htmlwidgets is not required, but shiny 0.12 will not work with older versions of htmlwidgets, so it’s a good idea to install a fresh copy along with Shiny.

Interactive plots with base graphics and ggplot2

Excluding points

The major new feature in this version of Shiny is the ability to create interactive plots using R’s base graphics or ggplot2. Adding interactivity is easy: it just requires using one option in plotOutput(), and then the information about mouse events will be available via the input object.

You can use mouse events to read mouse coordinates, select or deselect points, and implement zooming. Here are some example applications:

For more information, see the Interactive Plots articles in the Shiny Dev Center, and the demo apps in the gallery.

Switch from RJSONIO to jsonlite

Shiny uses the JSON format to send data between the server (running R) and the client web browser (running JavaScript).

In previous versions of Shiny, the data was serialized to/from JSON using the RJSONIO package. However, as of 0.12.0, Shiny switched from RJSONIO to jsonlite. The reasons for this are that jsonlite has better-defined conversion behavior, and it has better performance because much of it is now implemented in C.

For the vast majority of users, this will have no impact on existing Shiny apps.

The htmlwidgets package has also switched to jsonlite, and any Shiny apps that use htmlwidgets also require an upgrade to that package.

A note about Data Tables

The version we just released to CRAN is actually 0.12.1; the previous version, 0.12.0, was released three weeks ago and deprecated Shiny’s dataTableOutput and renderDataTable functions and instructed you to migrate to the nascent DT package instead. (We’ll talk more about DT in a future blog post.)

User feedback has indicated this transition was too sudden and abrupt, so we’ve undeprecated these functions in 0.12.1. We’ll continue to support these functions until DT has had more time to mature.

“Master” R in Washington DC this September!

Join RStudio Chief Data Scientist Hadley Wickham at the AMA – Executive Conference Center in Arlington, VA on September 14 and 15, 2015 for this rare opportunity to learn from one of the R community’s most popular and innovative authors and package developers.

It will be at least another year before Hadley returns to teach his class on the East Coast, so don’t miss this opportunity to learn from him in person. The venue is conveniently located next to Ronald Reagan Washington National Airport and a short distance from the Metro. Attendance is limited. Past events have sold out.

Register today!

HadleyWickhamHSJoin RStudio Chief Data Scientist Hadley Wickham at the University of Illinois at Chicago, on Wednesday May 27th & 28th for this rare opportunity to learn from one of the R community’s most popular and innovative authors and package developers.

As of this post, the workshop is two-thirds sold out. If you’re in or near Chicago and want to boost your R programming skills, this is Hadley’s only Central US public workshop planned for 2015.

Register here: https://rstudio-chicago.eventbrite.com

Devtools 1.8 is now available on CRAN. Devtools makes it so easy to build a package that it becomes your default way to organise code, data and documentation. You can learn more about developing packages at http://r-pkgs.had.co.nz/.

Get the latest version of devtools with:

install.packages("devtools")

There are three main improvements:

  • More helpers to get you up and running with package development as quickly as possible.

  • Better tools for package installation (including checking that all dependencies are up to date).

  • Improved reverse dependency checking for CRAN packages.

There were many other minor improvements and bug fixes. See the release notes for complete list of changes. The last release announcement was for devtools 1.6 since there weren’t many big changes in devtools 1.7. I’ve included the most important points in this announcement labelled with [1.7]. ## Helpers

The number of functions designed to get you up and going with package development continues to grow. This version sees the addition of:

  • dr_devtools(), which runs some common diagnostics: are you using the latest version of R and devtools? Similarly, dr_github() checks for common git/github configuration problems.

  • lint() runs lintr::lint_package() to check the style of package code [1.7].

  • use_code_of_conduct() adds a contributor code of conduct from http://contributor-covenant.org.

  • use_cran_badge() adds a CRAN status badge that you can copy into a README file. Green indicates package is on CRAN. Packages not yet submitted or accepted to CRAN get a red badge.

  • use_cran_comments() creates a cran-comments.md template and adds it to .Rbuildignore to help with CRAN submissions. [1.7]

  • use_coveralls() allows you to easily add test coverage with coveralls.

  • use_git() sets up a package to use git, initialising the repo and checking the existing files.

  • use_test() adds a new test file in tests/testthat.

  • use_readme_rmd() sets up a template to generate a README.md from a README.Rmd with knitr. [1.7]

Package installation and info

When developing packages it’s common to run into problems because you’ve updated a package, but you’ve forgotten to update it’s dependencies (install.packages() doesn’t this automatically). The new package_deps() solves this problem by finding all recursive dependencies of a package and determining if they’re out of date:

# Find out which dependencies are out of date
devtools::package_deps("devtools")
# Update them
update(devtools::package_deps("devtools"))

This code is used in install_deps() and revdep_check() – devtools is now aggressive about updating packages, which should avoid potential problems in CRAN submissions.
New update_packages() uses these tools to install a package (and its dependencies) only if they’re not already installed and current.

Reverse dependency checking

Devtools 1.7 included considerable improvement to reverse dependency checking. This sort of checking is important if your package gets popular, and is used by other CRAN packages. Before submitting updates to CRAN, you need to make sure that you have not broken the CRAN packages that use your package. Read more about it in the R packages book. To get started, run use_revdep(), then run the code in revdep/check.R.

I’m very excited to announce the 1.0.0 release of the stringr package. If you haven’t heard of stringr before, it makes string manipulation easier by:

  • Using consistent function and argument names: all functions start with str_, and the first argument is always the input string This makes stringr easier to learn and easy to use with the pipe.
  • Eliminating options that you don’t need 95% of the time.

To get started with stringr, check out the new vignette.

What’s new?

The biggest change in this release is that stringr is now powered by the stringi package instead of base R. This has two big benefits: stringr is now much faster, and has much better unicode support.

If you’ve used stringi before, you might wonder why stringr is still necessary: stringi does everything that stringr does, and much much more. There are two reasons that I think stringr is still important:

  1. Lots of people use it already, so this update will give many people a performance boost for free.
  2. The smaller API of stringr makes it a little easier to learn.

That said, once you’ve learned stringr, using stringi should be easy, so it’s a great place to start if you need a tool that doesn’t exist in stringr.

New features and functions

  • str_replace_all() gains a convenient syntax for applying multiple pairs of pattern and replacement to the same vector:
    x <- c("abc", "def")
    str_replace_all(x, c("[ad]" = "!", "[cf]" = "?"))
    #> [1] "!b?" "!e?"
  • str_subset() keeps values that match a pattern:
    x <- c("abc", "def", "jhi", "klm", "nop")
    str_subset(x, "[aeiou]")
    #> [1] "abc" "def" "jhi" "nop"
  • str_order() and str_sort() sort and order strings in a specified locale. str_conv() to converts strings from specified encoding to UTF-8.
    # The vowels come before the consonants in Hawaiian
    str_sort(letters[1:10], locale = "haw")
    #>  [1] "a" "e" "i" "b" "c" "d" "f" "g" "h" "j"
  • New modifier boundary() allows you to count, locate and split by character, word, line and sentence boundaries.
    words <- c("These are   some words. Some more words.")
    str_count(words, boundary("word"))
    #> [1] 7
    str_split(words, boundary("word"))
    #> [[1]]
    #> [1] "These" "are"   "some"  "words" "Some"  "more"  "words"

There were two minor changes to make stringr a little more consistent:

  • str_c() now returns a zero length vector if any of its inputs are zero length vectors. This is consistent with all other functions, and standard R recycling rules. Similarly, using str_c("x", NA) now yields NA. If you want "xNA", use str_replace_na() on the inputs.
  • str_match() now returns NA if an optional group doesn’t match (previously it returned “”). This is more consistent with str_extract() and other match failures.

Development

Stringr is over five years old and is quite stable (the last release was over two years ago). Although I’ve endeavoured to make the change to stringi as seemless as possible, it’s likely that it has created some new bugs. If you have problems, please try the development version, and if that doesn’t help, file an issue on github.

I’m pleased to announced that the first version of xml2 is now available on CRAN. Xml2 is a wrapper around the comprehensive libxml2 C library that makes it easier to work with XML and HTML in R:

  • Read XML and HTML with read_xml() and read_html().
  • Navigate the tree with xml_children(), xml_siblings() and xml_parent(). Alternatively, use xpath to jump directly to the nodes you’re interested in with xml_find_one() and xml_find_all(). Get the full path to a node with xml_path().
  • Extract various components of a node with xml_text(), xml_attrs(), xml_attr(), and xml_name().
  • Convert to list with as_list().
  • Where appropriate, functions support namespaces with a global url -> prefix lookup table. See xml_ns() for more details.
  • Convert relative urls to absolute with url_absolute(), and transform in the opposite direction with url_relative(). Escape and unescape special characters with url_escape() and url_unescape().
  • Support for modifying and creating xml documents in planned in a future version.

This package owes a debt of gratitude to Duncan Temple Lang who’s XML package has made it possible to use XML with R for almost 15 years!

Usage

You can install it by running:

install.packages("xml2")

(If you’re on a mac, you might need to wait a couple of days – CRAN is busy rebuilding all the packages for R 3.2.0 so it’s running a bit behind.)

Here’s a small example working with an inline XML document:

library(xml2)
x <- read_xml("<foo>
  <bar>text <baz id = 'a' /></bar>
  <bar>2</bar>
  <baz id = 'b' /> 
</foo>")

xml_name(x)
#> [1] "foo"
xml_children(x)
#> {xml_nodeset (3)}
#> [1] <bar>text <baz id="a"/></bar>
#> [2] <bar>2</bar>
#> [3] <baz id="b"/>

# Find all baz nodes anywhere in the document
baz <- xml_find_all(x, ".//baz")
baz
#> {xml_nodeset (2)}
#> [1] <baz id="a"/>
#> [2] <baz id="b"/>
xml_path(baz)
#> [1] "/foo/bar[1]/baz" "/foo/baz"
xml_attr(baz, "id")
#> [1] "a" "b"

Development

Xml2 is still under active development. If notice any problems (including crashes), please try the development version, and if that doesn’t work, file an issue.

I’m pleased to announced that the first version of readxl is now available on CRAN. Readxl makes it easy to get tabular data out of excel. It:

  • Supports both the legacy .xls format and the modern xml-based .xlsx format. .xls support is made possible the with libxls C library, which abstracts away many of the complexities of the underlying binary format. To parse .xlsx, we use the insanely fast RapidXML C++ library.
  • Has no external dependencies so it’s easy to use on all platforms.
  • Re-encodes non-ASCII characters to UTF-8.
  • Loads datetimes into POSIXct columns. Both Windows (1900) and Mac (1904) date specifications are processed correctly.
  • Blank columns are automatically dropped.
  • Returns output with class c("tbl_df", "tbl", "data.frame") so if you also use dplyr you’ll get an enhanced print method (i.e. you’ll see just the first ten rows, not the first 10,000!).

You can install it by running:

install.packages("readxl")

There’s not really much to say about how to use it:

library(readxl)
# Use a excel file included in the package
sample <- system.file("extdata", "datasets.xlsx", package = "readxl")

# Read by position
head(read_excel(sample, 2))
#>    mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> 1 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#> 2 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#> 3 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#> 4 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
#> 5 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
#> 6 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

# Or by name:
excel_sheets(sample)
#> [1] "iris"     "mtcars"   "chickwts" "quakes"
head(read_excel(sample, "mtcars"))
#>    mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> 1 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#> 2 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#> 3 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#> 4 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
#> 5 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
#> 6 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

You can see the documentation for more info on the col_names, col_types and na arguments.

Readxl is still under active development. If you have problems loading a dataset, please try the development version, and if that doesn’t work, file an issue.

Follow

Get every new post delivered to your Inbox.

Join 19,096 other followers