3 Programming with functions
3.1 āļø Overview
The basic question I asked while developing tabler
was how do you pass a function as an argument to another function.
This chapter still needs a lot of work.
3.2 š Useful websites
3.3 š¦ Load packages
library(dplyr, warn.conflicts = FALSE)
3.4 š¢ Simulate data
Here we simulate a small data set that is intended to be representative of data from a research study.
set.seed(123)
<- tibble(
study id = as.character(seq(1001, 1020, 1)),
sex = factor(sample(c("Female", "Male"), 20, TRUE)),
date = sample(seq.Date(as.Date("2021-09-15"), as.Date("2021-10-26"), "day"), 20, TRUE),
days = sample(1L:21L, 20L, TRUE),
height = rnorm(20, 71, 10)
)
# Add missing values for testing
$id[3] <- NA
study$sex[4] <- NA
study$date[5] <- NA
study$days[6] <- NA
study$height[7] <- NA study
3.5 Examples
This needs to be cleaned up. Iām just in a rush.
# Function passed to a function?
<- function(x) {
fn_number
x
}
fn_number(3)
[1] 3
<- function(n, fn) {
fn_sum 1 + fn(n)
}
fn_sum(3, fn_number)
[1] 4
<- function(x, f, ...) {
lapply2 <- vector("list", length(x))
out for (i in seq_along(x)) {
<- f(x[[i]], ...)
out[[i]]
}
out
}
lapply2(select(study, days, height), mean)
[[1]]
[1] NA
[[2]]
[1] NA
lapply2(select(study, days, height), mean, na.rm = TRUE)
[[1]]
[1] 12.05263
[[2]]
[1] 72.33294
# How do I make this work like purrr, dplyr, etc.
lapply2(select(study, days, height), ~ mean(.x, na.rm = TRUE))
Error in f(x[[i]], ...): could not find function "f"