22  Exercises for ‘Writing functions’ chapter ✎ Polishing

These exercises accompany the Writing Functions chapter.

You can complete these exercises in your local version of the .qmd file. Either download a copy of the whole book from github (see introduction), or download this .qmd using the download button on the top right of the page.

Write functions for each of the following. Remember that you can write pseudocode first if it helps.

22.1 Converting and tidying

22.1.1 Convert milliseconds to seconds

22.1.2 Convert n_months to n_years and round all values up the next year

Use ceiling() to round all values ending in something other than .0 up to the next whole value.

22.1.3 Remove the ’ ms’ suffix from data like “2000 ms”

Use the {stringr} library.

22.1.4 Tidy messy open-ended gender data

You can use the dat_depression_rct tibble that was created above.

22.1.5 Tidy messy age data

You can use the dat_depression_rct tibble that was created above.

22.2 Summarizing

22.2.1 Calculate mean by group

You can use the dat_depression_rct tibble that was created above.

What additional arguments might this benefit from to avoid it breaking under common use cases?

22.2.2 Calculate mean, SD, and N by group

You can use the dat_depression_rct tibble that was created above.

#
  
data <- dat_depression_rct


calc_summary <- function(data, grouping, variable){
  output <- data %>%
    group_by({{ grouping }}) %>%
    summarize(mean = mean({{ variable }}),
              sd = sd({{ variable }}),
              n = n())
  return(output)
}


calc_summary(dat_depression_rct, group, score)
group mean sd n
control 19.40 5.79 20
treatment 22.45 5.77 20

22.2.3 Mean, SD, and N by group, and differences in means between groups

You can use the dat_depression_rct tibble that was created above.

Pivot the result to wider format before mutating the difference in means.