I fell out with tapply and in love with dplyr

October 15, 2018

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

A long time ago (5 years) I wrote a blog post on tapply. Back then I was just getting into programming and I thought the possibilities of tapply were amazing. So it seems, do many others as it’s become one of my most viewed articles.

However, I never use tapply these days because the output is either a named vector or a matrix. Both of these require munging if I’m going to use the output. Three months after I wrote my tapply post a little package called dplyr was released. It took a while before it became integral to my workflow (I like to use as few packages as possible), but now I use it almost daily. The two biggest reasons are:

  1. A data frame as output
  2. Readable code.

Now we’re all living in the tidyverse, I’m a bit confused that so many folk still land on my blog looking for tapply. So this post updates/supersedes what I wrote previously. I’ve repeated the toy example I made before:

# Generate an example time series
df = data.frame(date=seq.Date(as.Date("1990-01-01"),

# Add some data (0s and 1s)
df = df %>%
   mutate(snow_lying=sample(c(0, 1), nrow(df), replace=T))

# Get month and year from date
df = df %>%
   mutate(month=format(date, "%m"),
          year=format(date, "%Y"))

# Sum for each month
df %>%
   group_by(month) %>%

# Sum for each month, each year
df %>%
   group_by(year, month) %>%

Read more about dplyr here: https://dplyr.tidyverse.org/

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

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...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)