Tidy Evaluation & Data Masking

Quick note on quo, enquo, and {{var}} commands when using a function that calls a dataframe in R. For Hadley’s documentation, see this website, or this one.

Here is the data.

id others pressure performance
1 0 0 6.134445
1 0 1 8.956932
1 0 2 8.435113
1 1 0 13.820419
1 1 1 15.473562
1 1 2 5.466076
1 2 0 10.331524
1 2 1 7.717611
1 2 2 7.990309
2 0 0 10.823559
2 0 1 6.930184
2 0 2 4.541806
2 1 0 7.996631
2 1 1 9.822106
2 1 2 12.640498
2 2 0 10.805539
2 2 1 9.941262
2 2 2 8.425159
3 0 0 5.772006
3 0 1 4.498032
3 0 2 9.525057
3 1 0 12.263280
3 1 1 7.263611
3 1 2 12.399793
3 2 0 14.471659
3 2 1 6.710794
3 2 2 8.397338

I want to take the commands below

ggplot(df %>% filter(pressure == 0), aes(x = as.factor(others), y = performance)) + 
  geom_violin(trim = F) + 
  theme_classic() + 
  xlab("Others Watching") + 
  ylab("Performance") + 
  theme(axis.text.y = element_blank(),
        axis.ticks.y = element_blank()) + 
  ggtitle("Pressure = 0")

and create a function. Here it is:

boxfunc <- function(col, title){
  col <- enquo(col)
  
  # use !! here
  ggplot(df %>% filter(pressure == !!col), aes(x = as.factor(others), y = performance)) + 
  geom_violin(trim = F) + 
  theme_classic() + 
  xlab("Others Watching") + 
  ylab("Performance") + 
  theme(axis.text.y = element_blank(),
        axis.ticks.y = element_blank()) + 
  # use parameter here
  ggtitle(paste("Pressure =", title, sep = " "))
  
}

Now use it.

boxfunc(0, 1)
boxfunc(1, 2)

Note that I can’t use boxfunc(quo(0),1) because R functions can’t handle a quo alongside a second parameter. Instead, I had to use enquo within the function.

You could also use a {{var}} approach:

varfunc <- function(col, title){
  
  # use {{var}} here
  ggplot(df %>% filter(pressure == {{col}}), aes(x = as.factor(others), y = performance)) + 
  geom_violin(trim = F) + 
  theme_classic() + 
  xlab("Others Watching") + 
  ylab("Performance") + 
  theme(axis.text.y = element_blank(),
        axis.ticks.y = element_blank()) + 
  # use parameter here
  ggtitle(paste("Pressure =", title, sep = " "))
  
}
varfunc(0, 1)

Bo\(^2\)m =)