%$% : upping your pipe game

Problem

What do I do when %>% doesn’t work?

Context

I love the %>%  pipe. Originally from magrittr, it’s now characteristic of tidy code. Using %>% has revolutionized how I write code in R (pssst! coming soon: an interactive pipe tutorial!). But sometimes the basic pipe falls short.

table() is one of my favorite functions for exploring data in R: it creates a frequency table of values in a vector. I use table() to do sanity checks on my data, make sure that all factor levels are present, and generally get a sense of how my observations are distributed.

A while back, though, I noticed that table() didn’t play nice with the %>% pipe.

I’ve collected some data on my friends’ pets. Here it is (using pseudonyms, in case anyone has a secret pet they don’t want the world to know about…).

83990007_811783839284749_7737077640338604032_n
This is one of the cats in the data frame below. She would like to hold your hand.
# Load magrittr
> library(magrittr)

# Create data
> pets <- data.frame(friend = c("Mark", "Mark", "Kyle", "Kyle", "Miranda", "Kayla", "Kayla", "Kayla", "Adriana", "Adriana", "Alex", "Randy", "Nancy"),
                   pet = c("cat", "cat", "cat", "cat", "cat", "dog", "cat", "lizard", "cat", "cat", "dog", "dog", "woodpecker"),
                   main_pet_color = c("brown", "brown", "multi", "multi", "brown", "brown", "brown", "orange", "black", "white", "multi", "white", "multi"))

# Look at the data
> pets
    friend        pet main_pet_color
1     Mark        cat          brown
2     Mark        cat          brown
3     Kyle        cat          multi
4     Kyle        cat          multi
5  Miranda        cat          brown
6    Kayla        dog          brown
7    Kayla        cat          brown
8    Kayla     lizard         orange
9  Adriana        cat          black
10 Adriana        cat          white
11    Alex        dog          multi
12   Randy        dog          white
13   Nancy woodpecker          multi

Unsurprisingly, it looks like there are a lot of cats and dogs! There are also a lot of brown pets and a lot of multicolored ones. Let’s say I want to see a frequency table of the pet colors. I know that I can do this with table(), like so:

# Make a frequency table of pet colors
> table(pets$main_pet_color)
 black  brown  multi orange  white 
     1      5      4      1      2

But if I want to use tidy syntax, I’d try to do it this way instead:

# Make a frequency table of pet colors
> pets %>% table(main_pet_color)
Error in table(., main_pet_color) : object 'main_pet_color' not found

What’s up with this? The syntax should work. pet is definitely a valid variable name in the data frame pets, and if I had used a different function, like arrange(), I would have had no problems:

# Arrange the data frame by pet color
> pets %>% arrange(main_pet_color)
    friend        pet main_pet_color
1  Adriana        cat          black
2     Mark        cat          brown
3     Mark        cat          brown
4  Miranda        cat          brown
5    Kayla        dog          brown
6    Kayla        cat          brown
7     Kyle        cat          multi
8     Kyle        cat          multi
9     Alex        dog          multi
10   Nancy woodpecker          multi
11   Kayla     lizard         orange
12 Adriana        cat          white
13   Randy        dog          white

So why doesn’t this work with table()?? This problem has driven me crazy on several occasions. I always ended up reverting back to the table(pets$main_pet_color) syntax, but I was not happy about it.

Turns out, there’s a simple fix.

Continue reading “%$% : upping your pipe game”

Some lessons from rstudio::conf

Today I’m departing a little from the problem/context/solution format of these posts to share some things I learned from last week’s rstudio::conf.

When I started in R a few years ago, I never thought I would have any place at a coding conference for computer people. But thanks to some help from my lab and my college, last week I flew out to sunny San Francisco for the 2020 rstudio::conf, and I had a blast! Here are some things I learned and some avenues I’m excited to explore in the future.

1. The R community is (actually) awesome.

horst_bof_buttons
This art is by RStudio artist-in-residence Allison Horst. She does amazing illustrations! You can find her work on her GitHub page, and she’s on twitter @allison_horst.

I was pretty nervous to attend this conference. I’ve never really considered myself a computer person, and I learned R pretty much accidentally through my work in biology. In my experience, people who do a lot of computer programming tend to use a lot of intimidating jargon, and I was scared I’d flounder.

I was surprised at how genuinely welcome I felt. At meals and talks, I sat down next to random people and asked what they did or how they knew R. I met people with so many diverse interests! Among others:

A linguist now working for a nonprofitA neuroscience PhD now working for FacebookSeveral young professors teaching data science at their schoolsA woman who flew from Brazil (!!) to attend the conferenceSomeone just getting to know RTwo young people who interned at RStudio, despite not being experts in RAn RStudio bigwig (swoon!)A professor working on genomic dataA researcher at the SmithsonianAn aquatic ecologist who uses R for workSo many people! You get the gist.

And they were all happy to talk to me!

2. So much happens on Twitter.

I joined Twitter on a whim this fall, and it has been awesome. I learned about this conference through Twitter. I’ve found some internships through Twitter. And by following the #rstats hashtag and some key people in the R community, I’ve learned all sorts of tips and tricks about the kinds of things you can do with Twitter.

Apart from that, lots of people were live-tweeting the rstudio::conf, and I tried my hand at that, too! A highlight was when the one and only Hadley Wickham liked one of my tweets.

3. I need to start making Shiny apps.

As I said in my tweet (the one that Hadley liked!), this conference convinced me that I really should start building apps with RShiny as soon as possible.

Why haven’t I done this already?

The main reason is that the word “app” strikes fear into my heart. Surely I can’t develop an app??

Shiny apps are web apps, which is a little less intimidating, somehow. The basic gist of Shiny apps is that they are ways to explore your data interactivelyThat’s it. Some Shiny apps can get pretty complicated. For example, here’s a cool dashboard for visualizing tweets about the 2019 rstudio::conf. As you can see, it’s pretty fancy.

Screen Shot 2020-02-03 at 16.07.03

But Shiny apps can also be pretty simple, like this one, which shows a simple histogram of the duration of eruptions of the Old Faithful geyser:

Screen Shot 2020-02-03 at 16.09.35

This app just lets the user change the number of histogram bins, include a density curve, and show the individual observations on the x axis. Pretty simple, but still so much better than a static visualization! I really have no excuse not to make something like this.

In particular, I can’t wait to build an app for the Yale Grammatical Diversity Project (YGDP). I’m currently working with the YGDP to help organize their database of linguistic survey data. I’ve already created some reports in RMarkdown to help visualize the data (you can see an example here). But wouldn’t this be so much better if it were interactive??

Screen Shot 2020-02-03 at 16.14.22
Note: I’m loving the viridis color palette in this graph. So much better than the ggplot2 default!

4. Bonus: fun with hex stickers

I finally got to experience the hype about hexagon stickers for R packages. They are so pretty and fun, and they fit together so nicely! I picked up a whole bunch:

20200130_210818

And, funnily enough, I’ve been playing with hexagons as wall decorations for a while now, before I even knew about hex stickers…

20190825_212331

…so obviously, the possibilities now are truly endless. Hexagons on hexagons? A hex collage on the wall and one on my computer? Wow.

That’s all for now! Soon (I hope), I’ll post highlights from talks at the conference, because, well, I guess those were cool too.

if ifelse() had more if’s, AND an else

Problem

The case_when() function in dplyr is great for dealing with multiple complex conditions (if’s). But how do you specify an “else” condition in case_when()?

Context

Last month, I was super excited to discover the case_when() function in dplyr. But when I showed my blog post to a friend, he pointed out a problem: there seemed to be no way to specify a “background” case, like the “else” in ifelse(). In the previous post, I gave an example with three outcomes based on test results. The implication was that there would be roughly equal numbers of people in each group. But what if the vast majority of people failed both tests, and we really just wanted to filter out the ones who didn’t?

Today, I came across exactly this problem in my research. I’m analyzing morphometric data for about 500 tadpoles, and I made a PCA score plot that looked like this:

Screen Shot 2019-11-22 at 12.48.01 PM

Before continuing my analysis, I wanted to take a closer look at those outlier points, to make sure they represent real measurements and not mistakes in the data. Specifically, I wanted to take a look at these ones:

Screen Shot 2019-11-22 at 12.48.01 PM copy.png

To figure out which tadpoles to investigate, I’d have to pull out their names based on their scores on the PC1 and PC2 axes.

Solution

I decided to add a column called investigate to the PCA scores data frame, set to “investigate” or “ok” depending on whether the observation in question needed to be looked at.

scores <- scores %>% 
          mutate(investigate = case_when(PC1 > 0.2 ~ "investigate",
                                         PC2 > 0.15 ~ "investigate",
                                         PC1 < -0.1 & PC2 > 0.1 ~ "investigate,
                                         TRUE ~ "ok"))

What’s up with that weird TRUE ~ "ok" line at the end of the ​​case_when() statement? Basically, that’s the equivalent of else.  It translates, roughly, to “assign anything that’s left to “ok.”

I’m really not sure why the equivalent of else here is TRUE, and the ​case_when documentation doesn’t really explain it. The only way I figured out that this worked was by reading through the examples in the documentation and noticing that they all seemed to end with this TRUE ~ statement, so I tried it, and voilà. If anyone has an understanding of why this works, under the hood, I’d love to know!

One thing to note is that the order of arguments matters here. If we had started off with the TRUE ~ "ok" statement and then specified the other conditions, it wouldn’t have worked: everything would just get assigned to “ok.”

I’m really glad I figured out how to add an else to case_when()! Before I started using dplyr, I would have attempted this problem like this:

scores$investigate <- "ok" # Create a whole column filled with "ok"
scores$investigate[scores$PC1 > 0.2] <- "investigate"
scores$investigate[scores$PC2 > 0.15] <- "investigate"
scores$investigate[scores$PC1 < -0.1 & scores$PC2 > 0.1] <- "investigate"

Or maybe I would have used some really long and complex boolean statement to get all those conditions in one line of code. Or nested ifelse‘s. But that’s annoying and hard to read. This is so much neater, and saves typing!

Outcome

It turns out that if you read the documentation closely, case_when()is a fully-functioning version of ifelse that allows for multiple if statements AND a background condition (else). The more I learn about the tidyverse, the more I love it.

 

Loading packages efficiently

Problem

Especially in a project with many different scripts, it can be challenging to keep track of all the packages you need to load. It’s also easy to lose track of whether or not you’ve incorporated package loading into the script itself until you switch to a new computer or restart R and all of a sudden, your packages need to be re-loaded.

Context

When I was first starting out in R, I learned quickly to load packages all together at the top of a script, not along the way as I needed them. But it took a while, until I started using R Projects, before I decided to centralize package loading above the script level. I was sick of having to deal with loading the right packages at the right times, so I decided to just streamline the whole thing.

Solution

Make a separate R script, called “libraries.R” or “packages.R” or something. Keep it consistent. Mine is always called “libraries,” and I keep it in my project folder.

libraries.PNG

It looks something like this (individual libraries may vary, of course):

librariesscript

Then, at the top of each analysis script, I can simply source the libraries script, and all the libraries I need load automatically.

loading the libraries.PNG

Outcome

I can easily load libraries in the context of a single R Project, keep track of which ones are loaded, and not have to worry about making my scripts look messy with a whole chunk of library() commands at the top of each one. It’s also straightforward to pop open the “libraries” script whenever I want to add a new library or delete one.

 

if ifelse() had more if’s

Problem

The ifelse() function only allows for one “if” statement, two cases. You could add nested “if” statements, but that’s just a pain, especially if the 3+ conditions you want to use are all on the same level, conceptually. Is there a way to specify multiple conditions at the same time?

Context

I was recently given some survey data to clean up. It looked something like this (but obviously much larger):

tabletest.png

I needed to classify people in this data set based on whether they had passed or failed certain tests.

I wanted to separate the people into three groups:

  • People who passed both tests: Group A
  • People who passed one test: Group B
  • People who passed neither test: Group C

I thought about using a nested ifelse statement, and I certainly could have done that. But that approach didn’t make sense to me. The tests are equivalent and not given in any order; I simply want to sort the people into three equal groups. Any nesting of “if” statements would seem to imply a hierarchy that doesn’t really exist in the data. Not to mention that I hate nesting functions. It’s confusing and hard to read. 

Continue reading “if ifelse() had more if’s”

Initializing an empty list

Problem

How do I initialize an empty list for use in a for-loop or function?

Context

Sometimes I’m writing a for-loop (I know, I know, I shouldn’t use for-loops in R, but sometimes it’s just easier. I’m a little less comfortable with apply functions than I’d like to be) and I know I’ll need to store the output in a list. Once in a while, the new list will be similar in form to an existing one, but more often, I just need to start from scratch, knowing only the number of elements I want to include.

This isn’t a totally alien thing to need to do––it’s pretty familiar if you’re used to initializing empty vectors before for-loops. There’s a whole other debate to be had about whether or not it’s acceptable to start with a truly empty vector and append to it on every iteration of the loop or whether you should always know the length beforehand, but I’ll just focus on the latter case for now.

Anyway, initializing a vector of a given length is easy enough; I usually do it like this:

> desired_length <- 10 # or whatever length you want
> empty_vec <- rep(NA, desired_length)

I couldn’t immediately figure out how to replicate this for a list, though. The solution turns out to be relatively simple, but it’s just different enough that I can never seem to remember the syntax. This post is more for my records than anything, then.

Continue reading “Initializing an empty list”

(Automatically Show Output)

Problem

It’s annoying to have to type the name of an object I just created in order to print its output in a script.

Context

A certain lightsaber-wielding stats professor of mine liked to point out that R doesn’t go out of its way to be helpful. If you write a line of code that creates an object and then run that line of code, there’s no message to tell you that the object has been successfully created. R doesn’t say “Task complete! What’s next?” or otherwise give you any indication that anything has happened. To actually view the object you just created, you have to type its name or run some other command on it.

Once in a while, this lack of transparency can be frustrating. What if I want to save objects and also view them in real time as they are created? Say I’ve used the handy prop.table function to transform a frequency table into a proportion table. I’d like to be able to view prop, prop.1 and prop.2 without typing their names and adding extra lines of code.

Continue reading “(Automatically Show Output)”