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)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.
- Write a function
summarize_var_new()that which returns the median, 25% percentile, and 75% percentile of a variable. Use{{ }}.
- Add a
groupargument 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 = NULLdo?)
summarize_var_new(nlsy, income, sex_cat)
summarize_var_new(nlsy, income) # should still workWrite 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.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!
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
- Programming with dplyr – the official guide to
{{ }}and.data[[ ]] - R for Data Science: Functions
- Advanced R
{purrr}documentation, if you want to go further withmap()