2.7 Functions that take variables

Open the slides in a new tab here.

Exercises

Download the tidyeval-examples.R script and add it to your in-class project folder. It has all the examples from the slides, plus these exercises at the bottom.

  1. Write a function summarize_var_new() that which returns the median, 25% percentile, and 75% percentile of a variable. Use {{ }}.
summarize_var_new <- function(data, variable) {

}

# test on a few variables
summarize_var_new(nlsy, income)
summarize_var_new(nlsy, age_bir)
summarize_var_new(nlsy, nsibs)
  1. Add a group argument so the summary can be stratified, using .by = {{ group }}. Give it a sensible default so the function still works when you don’t pass a group. (Hint: what does .by = NULL do?)
summarize_var_new(nlsy, income, sex_cat)
summarize_var_new(nlsy, income) # should still work
  1. Write a function summarize_two_vars() that takes a dataset and two variables and returns their correlation and covariance. Test it on income and age_bir, and on income and nsibs.

  2. Write a function that takes a dataset and a grouping variable and returns a {gtsummary} table stratified by it. Include whichever variables you like, and add at least one formatting function (bold_labels(), add_overall(), add_p(), modify_caption(), …).

table_by <- function(data, group) {

}

table_by(nlsy, sex_cat)
table_by(nlsy, region_cat)

Notice how much less work the second table was than the first!

Commit and push!

Tip

If your function works when you run its body line by line but fails when you call it, check whether you’ve wrapped the variable arguments in {{ }}. That’s the most common cause.

Resources