Code
library(tidyverse, quietly=TRUE)
library(lubridate, quietly=TRUE)
All of our examples will be based on a common data set. We’ll begin by creating it and explaining how it works.
Let’s say you are suffering from unexplained headaches that appear somewhat randomly. You suspect they may be associated with something you eat, but you’re not sure, so you’ve been tracking 14 weeks (98 days) worth of your own data in a spreadsheet that looks like this:
library(tidyverse, quietly=TRUE)
library(lubridate, quietly=TRUE)
set.seed(1984)
<- tibble(date=seq(from = today()-weeks(14),
x by = "1 day", length.out = 7*14),
headache = sample(c(TRUE,FALSE), 7*14,
prob = c(.05,.95),
replace = TRUE))
::kable( head(x) ) %>% kableExtra::kable_styling() knitr
date | headache |
---|---|
2022-07-19 | FALSE |
2022-07-20 | FALSE |
2022-07-21 | FALSE |
2022-07-22 | FALSE |
2022-07-23 | FALSE |
2022-07-24 | FALSE |
write_csv(x,"headache-days.csv")
You can download a copy of this file here
It’s easy to add a few more variables (columns) to the dataframe: (download)
<- function(x){
z = NULL
m for(i in 1:14){
= c(c(rep(0,6),
m floor(runif(1,min=0,max=3))),
m)
}
m
}<- tibble(date=seq(from = today()-weeks(14),
x by = "1 day", length.out = 7*14),
headache = sample(c(TRUE,FALSE), 7*14,
prob = c(.05,.95),
replace = TRUE),
icecream = sample(c(TRUE,FALSE), 7*14,
prob = c(.10,.90),
replace = TRUE),
z = runif(7*14, min = -2.5, max = .5) + 8,
wine = z(0))
::kable( head(x,10), digits = 2) %>%
knitr::kable_styling(bootstrap_options = c("striped", "hover", "condensed")) kableExtra
date | headache | icecream | z | wine |
---|---|---|---|---|
2022-07-19 | FALSE | TRUE | 7.56 | 0 |
2022-07-20 | FALSE | FALSE | 7.38 | 0 |
2022-07-21 | FALSE | FALSE | 5.51 | 0 |
2022-07-22 | FALSE | TRUE | 7.60 | 0 |
2022-07-23 | FALSE | FALSE | 8.36 | 0 |
2022-07-24 | FALSE | FALSE | 6.92 | 0 |
2022-07-25 | FALSE | FALSE | 6.32 | 0 |
2022-07-26 | FALSE | FALSE | 7.52 | 0 |
2022-07-27 | FALSE | FALSE | 7.95 | 0 |
2022-07-28 | FALSE | FALSE | 6.99 | 0 |
write_csv(x,"headache-variables.csv")
headache
: a day when I have a headacheicecream
: did I eat ice cream that day?wine
: Number of glasses of wine I drank.z
: Number of hours I slept that day.