diff --git a/chapter 7 examples.qmd b/chapter 7 examples.qmd
new file mode 100644
index 0000000..35f9fff
--- /dev/null
+++ b/chapter 7 examples.qmd
@@ -0,0 +1,101 @@
+---
+title: "map() practice"
+author: "Schwab"
+editor: visual
+---
+
+```{r}
+library(tidyverse)
+library(mosaicData)
+```
+
+Doing problems 1 and 3 from [here](https://mdsr-book.github.io/mdsr3e/07-iteration.html#iteration-exercises)
+
+**Problem 1 (Easy)**: Use the `HELPrct` data from the `mosaicData` to calculate the mean of all numeric variables (be sure to exclude missing values).\
+
+```{r}
+HELPrct |>
+ summarise(
+ across(.cols = where(is.numeric),
+ .fns = ~mean(. , na.rm = TRUE))
+ )
+```
+
+**Problem 3 (Medium)**: Use routines from the `purrr` package and the `HELPrct` data frame from the `mosaicData` package to fit a regression model predicting `cesd` as a function of `age` separately for each of the levels of the `substance` variable. Generate a formatted table (with suitable caption) of results
+(estimates and confidence intervals) for the slope parameter for each level of the grouping variable.
+
+(Hint: Use `group_by()` and `group_modify()` to fit the regression model on each part. Note that `broom::tidy()` is useful in having the output of the model be a data frame.)
+
+```{r}
+HELPrct |> select(substance, cesd, age) |>
+group_by(substance)|>
+ group_modify(.f = ~broom::tidy( lm(cesd~age, data = .))) |>
+ filter(term =="age") |>
+ mutate(CI_low = estimate - 2*std.error, CI_high = estimate + 2*std.error) |>
+ select(-statistic, - p.value, - std.error) |>
+ kableExtra::kable(caption = "The likelyhood someone uses a substance increates with age.", digits = 1)
+```
+
+Activity 2
+
+Make a function that takes a df and a variable then produces a scatter plot of that variable vs cesd. Use it to plot multiple graphs of the first 6 numeric variables HELPrct. [Hint: check out the extended example from 7.7](https://mdsr-book.github.io/mdsr3e/07-iteration.html#extended-example-factors-associated-with-bmi)
+
+```{r}
+library(tidyverse)
+library(mosaicData)
+
+my_func <- function(data,variable2){
+ my_plot <- data |>
+ ggplot(aes(x = cesd))+
+ aes_string(y = variable2)+
+ geom_point()
+}
+
+numeric_names_only <- HELPrct |>
+ select("age":"d1")|>
+ names()
+
+
+map(.x = numeric_names_only,
+ .f = my_func,
+ data= HELPrct
+ )|>
+ patchwork::wrap_plots(ncol = 2)
+```
+
+
+```{r}
+library(tidyverse)
+library(mosaicData)
+
+my_func <- function(data,variable2){
+ my_plot <- data |>
+ ggplot(aes(x = cesd, y = {{variable2}}))+
+ geom_point()
+}
+
+my_func(HELPrct, age)
+
+```
+
+```{r}
+library(NHANES)
+
+bmi_plot <- function(.data, x_var) {
+ ggplot(.data, aes(y = BMI)) +
+ aes_string(x = x_var) +
+ geom_jitter(alpha = 0.3) +
+ geom_smooth() +
+ labs(
+ title = paste("BMI by", x_var),
+ subtitle = "NHANES",
+ caption = "US National Center for Health Statistics (NCHS)"
+ )
+}
+bmi_plot(NHANES, "Age")
+
+c("Age", "HHIncomeMid", "PhysActiveDays",
+ "TVHrsDay", "AlcoholDay", "Pulse") |>
+ map(bmi_plot, .data = NHANES) |>
+ patchwork::wrap_plots(ncol = 2)
+```
diff --git a/docs/chapter 7 examples.html b/docs/chapter 7 examples.html
new file mode 100644
index 0000000..0b103de
--- /dev/null
+++ b/docs/chapter 7 examples.html
@@ -0,0 +1,832 @@
+
+
Problem 3 (Medium): Use routines from the purrr package and the HELPrct data frame from the mosaicData package to fit a regression model predicting cesd as a function of age separately for each of the levels of the substance variable. Generate a formatted table (with suitable caption) of results (estimates and confidence intervals) for the slope parameter for each level of the grouping variable.
+
(Hint: Use group_by() and group_modify() to fit the regression model on each part. Note that broom::tidy() is useful in having the output of the model be a data frame.)
The likelyhood someone uses a substance increates with age.
+
+
+
substance
+
term
+
estimate
+
CI_low
+
CI_high
+
+
+
+
+
alcohol
+
age
+
0.3
+
0.1
+
0.6
+
+
+
cocaine
+
age
+
-0.3
+
-0.6
+
0.0
+
+
+
heroin
+
age
+
-0.2
+
-0.5
+
0.0
+
+
+
+
+
+
Activity 2
+
Make a function that takes a df and a variable then produces a scatter plot of that variable vs cesd. Use it to plot multiple graphs of the first 6 numeric variables HELPrct. Hint: check out the extended example from 7.7
Warning: `aes_string()` was deprecated in ggplot2 3.0.0.
+ℹ Please use tidy evaluation idioms with `aes()`.
+ℹ See also `vignette("ggplot2-in-packages")` for more information.
+
+
+
Warning: Removed 207 rows containing missing values or values outside the scale range
+(`geom_point()`).
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
+
+
+
Warning: Removed 366 rows containing non-finite outside the scale range
+(`stat_smooth()`).
+Removed 366 rows containing missing values or values outside the scale range
+(`geom_point()`).
+
+
+
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
+
+
+
Warning: Removed 1148 rows containing non-finite outside the scale range
+(`stat_smooth()`).
+
+
+
Warning: Removed 1148 rows containing missing values or values outside the scale range
+(`geom_point()`).
+
+
+
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
+
+
+
Warning: Removed 5442 rows containing non-finite outside the scale range
+(`stat_smooth()`).
+
+
+
Warning: Failed to fit group -1.
+Caused by error in `smooth.construct.cr.smooth.spec()`:
+! x has insufficient unique values to support 10 knots: reduce k.
+
+
+
Warning: Removed 5442 rows containing missing values or values outside the scale range
+(`geom_point()`).
+
+
+
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
+
+
+
Warning: Removed 366 rows containing non-finite outside the scale range
+(`stat_smooth()`).
+
+
+
Warning: Removed 366 rows containing missing values or values outside the scale range
+(`geom_point()`).
+
+
+
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
+
+
+
Warning: Removed 5113 rows containing non-finite outside the scale range
+(`stat_smooth()`).
+
+
+
Warning: Removed 5113 rows containing missing values or values outside the scale range
+(`geom_point()`).
+
+
+
`geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
+
+
+
Warning: Removed 1502 rows containing non-finite outside the scale range
+(`stat_smooth()`).
+
+
+
Warning: Removed 1502 rows containing missing values or values outside the scale range
+(`geom_point()`).
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/docs/chapter-7-examples_files/figure-html/unnamed-chunk-4-1.png b/docs/chapter-7-examples_files/figure-html/unnamed-chunk-4-1.png
new file mode 100644
index 0000000..10178e3
Binary files /dev/null and b/docs/chapter-7-examples_files/figure-html/unnamed-chunk-4-1.png differ
diff --git a/docs/chapter-7-examples_files/figure-html/unnamed-chunk-6-1.png b/docs/chapter-7-examples_files/figure-html/unnamed-chunk-6-1.png
new file mode 100644
index 0000000..b425cbe
Binary files /dev/null and b/docs/chapter-7-examples_files/figure-html/unnamed-chunk-6-1.png differ
diff --git a/docs/chapter-7-examples_files/figure-html/unnamed-chunk-6-2.png b/docs/chapter-7-examples_files/figure-html/unnamed-chunk-6-2.png
new file mode 100644
index 0000000..682bcfd
Binary files /dev/null and b/docs/chapter-7-examples_files/figure-html/unnamed-chunk-6-2.png differ
diff --git a/docs/index.html b/docs/index.html
index 49b7b96..a028617 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -2,12 +2,12 @@
-
+
-
+
SDS 192 - SDS 192: Intro to Data Science
@@ -114,9 +106,9 @@
-
+
Make a function that takes a df and a variable then produces a scatter plot of that variable vs cesd. Use it to plot multiple graphs of the first 6 numeric variables HELPrct. Hint: check out the extended example from 7.7
Walk to MCCo
return localAlternateSentinel;
}
}
- const darkModeDefault = false;
- let localAlternateSentinel = darkModeDefault ? 'alternate' : 'default';
+ let localAlternateSentinel = 'default';
// Dark / light mode switch
window.quartoToggleColorScheme = () => {
// Read the current dark / light value
let toAlternate = !hasAlternateSentinel();
toggleColorMode(toAlternate);
setStyleSentinel(toAlternate);
- toggleGiscusIfUsed(toAlternate, darkModeDefault);
};
// Ensure there is a toggle, if there isn't float one in the top right
if (window.document.querySelector('.quarto-color-scheme-toggle') === null) {
@@ -1177,27 +1095,10 @@
Walk to MCCo
// clear code selection
e.clearSelection();
});
- var localhostRegex = new RegExp(/^(?:http|https):\/\/localhost\:?[0-9]*\//);
- var mailtoRegex = new RegExp(/^mailto:/);
- var filterRegex = new RegExp('/' + window.location.host + '/');
- var isInternal = (href) => {
- return filterRegex.test(href) || localhostRegex.test(href) || mailtoRegex.test(href);
- }
- // Inspect non-navigation links and adorn them if external
- var links = window.document.querySelectorAll('a[href]:not(.nav-link):not(.navbar-brand):not(.toc-action):not(.sidebar-link):not(.sidebar-item-toggle):not(.pagination-link):not(.no-external):not([aria-hidden]):not(.dropdown-item):not(.quarto-navigation-tool)');
- for (var i=0; iWalk to MCCo
interactive: true,
interactiveBorder: 10,
theme: 'quarto',
- placement: 'bottom-start',
+ placement: 'bottom-start'
};
- if (contentFn) {
- config.content = contentFn;
- }
- if (onTriggerFn) {
- config.onTrigger = onTriggerFn;
- }
- if (onUntriggerFn) {
- config.onUntrigger = onUntriggerFn;
- }
window.tippy(el, config);
}
const noterefs = window.document.querySelectorAll('a[role="doc-noteref"]');
@@ -1229,130 +1121,7 @@
Walk to MCCo
try { href = new URL(href).hash; } catch {}
const id = href.replace(/^#\/?/, "");
const note = window.document.getElementById(id);
- if (note) {
- return note.innerHTML;
- } else {
- return "";
- }
- });
- }
- const xrefs = window.document.querySelectorAll('a.quarto-xref');
- const processXRef = (id, note) => {
- // Strip column container classes
- const stripColumnClz = (el) => {
- el.classList.remove("page-full", "page-columns");
- if (el.children) {
- for (const child of el.children) {
- stripColumnClz(child);
- }
- }
- }
- stripColumnClz(note)
- if (id === null || id.startsWith('sec-')) {
- // Special case sections, only their first couple elements
- const container = document.createElement("div");
- if (note.children && note.children.length > 2) {
- container.appendChild(note.children[0].cloneNode(true));
- for (let i = 1; i < note.children.length; i++) {
- const child = note.children[i];
- if (child.tagName === "P" && child.innerText === "") {
- continue;
- } else {
- container.appendChild(child.cloneNode(true));
- break;
- }
- }
- if (window.Quarto?.typesetMath) {
- window.Quarto.typesetMath(container);
- }
- return container.innerHTML
- } else {
- if (window.Quarto?.typesetMath) {
- window.Quarto.typesetMath(note);
- }
- return note.innerHTML;
- }
- } else {
- // Remove any anchor links if they are present
- const anchorLink = note.querySelector('a.anchorjs-link');
- if (anchorLink) {
- anchorLink.remove();
- }
- if (window.Quarto?.typesetMath) {
- window.Quarto.typesetMath(note);
- }
- // TODO in 1.5, we should make sure this works without a callout special case
- if (note.classList.contains("callout")) {
- return note.outerHTML;
- } else {
- return note.innerHTML;
- }
- }
- }
- for (var i=0; i res.text())
- .then(html => {
- const parser = new DOMParser();
- const htmlDoc = parser.parseFromString(html, "text/html");
- const note = htmlDoc.getElementById(id);
- if (note !== null) {
- const html = processXRef(id, note);
- instance.setContent(html);
- }
- }).finally(() => {
- instance.enable();
- instance.show();
- });
- }
- } else {
- // See if we can fetch a full url (with no hash to target)
- // This is a special case and we should probably do some content thinning / targeting
- fetch(url)
- .then(res => res.text())
- .then(html => {
- const parser = new DOMParser();
- const htmlDoc = parser.parseFromString(html, "text/html");
- const note = htmlDoc.querySelector('main.content');
- if (note !== null) {
- // This should only happen for chapter cross references
- // (since there is no id in the URL)
- // remove the first header
- if (note.children.length > 0 && note.children[0].tagName === "HEADER") {
- note.children[0].remove();
- }
- const html = processXRef(null, note);
- instance.setContent(html);
- }
- }).finally(() => {
- instance.enable();
- instance.show();
- });
- }
- }, function(instance) {
+ return note.innerHTML;
});
}
let selectedAnnoteEl;
@@ -1396,7 +1165,6 @@
Walk to MCCo
}
div.style.top = top - 2 + "px";
div.style.height = height + 4 + "px";
- div.style.left = 0;
let gutterDiv = window.document.getElementById("code-annotation-line-highlight-gutter");
if (gutterDiv === null) {
gutterDiv = window.document.createElement("div");
@@ -1422,32 +1190,6 @@
Walk to MCCo
});
selectedAnnoteEl = undefined;
};
- // Handle positioning of the toggle
- window.addEventListener(
- "resize",
- throttle(() => {
- elRect = undefined;
- if (selectedAnnoteEl) {
- selectCodeLines(selectedAnnoteEl);
- }
- }, 10)
- );
- function throttle(fn, ms) {
- let throttle = false;
- let timer;
- return (...args) => {
- if(!throttle) { // first call gets through
- fn.apply(this, args);
- throttle = true;
- } else { // all the others get throttled
- if(timer) clearTimeout(timer); // cancel #2
- timer = setTimeout(() => {
- fn.apply(this, args);
- timer = throttle = false;
- }, ms);
- }
- };
- }
// Attach click handler to the DT
const annoteDls = window.document.querySelectorAll('dt[data-target-cell]');
for (const annoteDlNode of annoteDls) {
@@ -1519,9 +1261,7 @@