Skip to main content

Section 2.7 Common Gotchas & Quick Fixes

Below are some common mistakes made in the tidyverse and ways to fix them. As always in R (and probably in life) if some code ever gets too frustrating, step away from your computer for a few minutes.

Subsection 2.7.1 = vs ==

In math, we use one equal sign. In tidyverse, we use two equal signs.
filter(species = "Adelie")  # WRONG

filter(species == "Adelie") # RIGHT

Subsection 2.7.2 NA-aware math

When doing math (inside or outside of tidyverse) NA values can mess up everything. Below is an example of this. We can utilize na.rm = command, which by default is set to β€œFALSE”.
mean(penguins$body_mass_g)                 # Returns NA if any missing

mean(penguins$body_mass_g, na.rm = TRUE)   # CORRECT
[1] NA
[1] 4201.754
As you can see, the addition of na.rm = "TRUE" removes the NA value and calculates the average.

Subsection 2.7.3 Pipe position

Piping is something that most R programmers use in some way or another. If you decide to use it, it is imperative that the pipe is placed on the line that you’re going to connect. Below is an example of a good and a bad (won’t work) piping.
penguins |>
  select(species)     # Good

penguins
|> select(species)   # Bad

Subsection 2.7.4 Conflicting function names

As mentioned before, there may be times where there are packages being loaded that have conflicting function names. For instance dplyr::filter vs stats::filter.

In the case when you need to specifically call the package with the command, make sure to use the formula:.

\(package::function()\)