Hi!
I just wanted to let you know that seagulls in Brighton are vicious, and they like overpriced bagels. Especially if they belong to someone else, so be wary.
Other than that, I decided to finally look into something I’ve been using a lot, but didn’t quite know what happens under the hood. Meet the ⭐%in% operator ⭐. Let’s imagine the following scenario:
You are chasing seagulls roosting next to the tourists’ favourite food places. Since you want to keep an eye on your enemies, you create a table. You use it to store information on whether seagulls already have chicks or if it's just an adult waiting to find the mate of their life. You know it’s important, because a single adult male is more likely to steal your doughnut to impress the gals, whereas couples prefer feeding their chicks with fries (please don’t quote me on that).
### Load the data ###
library(dplyr)
nests <- data.frame(
ID = 1:5,
Stage = c("chicks", "adult", "adult", "chicks", "adult"),
Sex = c("both", "female", "male", "both", "female")
)
One day, you want to find out how many single seagulls are on your list.
### Filter individuals of interest ###
nests_opt1 <- nests %>% filter(Stage %in% "adult")
Which gives you:
Great, that’s what we wanted. But the order of Stage %in% "adult" seems a bit off. So you try:
nests_opt2 <- nests %>% filter("adult" %in% Stage)
Hmmm… didn’t really work as intended:
The reason for this is that the %in% operator checks if a given element is present in a given vector, and then returns TRUE/FALSE values. However, the order in which we feed the element and the vector into it is important and changes the request.
With "adult" %in% Stage, we ask: “Is there an adult somewhere in the Stage column of our data frame?”
With Stage %in% "adult", it changes to: “Check each row of the Stage column and tell me whether it is an adult or not, which is exactly what we want for filtering.
Have a good evening,
Aga
PS: Here is the survey in which you can tell me what R topic you find particularly confusing and why you want to learn it so that we can shape this space together!