From f3db882d9d256116ba55e6d8b39285b8a424795e Mon Sep 17 00:00:00 2001 From: "Y. Yu" <54338793+PursuitOfDataScience@users.noreply.github.com> Date: Tue, 16 Aug 2022 12:37:44 -0400 Subject: [PATCH] Update iteration.qmd (#1071) Provided another way of getting R squared by using `nest()` from tidyr, which makes the code to be tidyverse consistent. --- iteration.qmd | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/iteration.qmd b/iteration.qmd index ce32147..fcdd3b5 100644 --- a/iteration.qmd +++ b/iteration.qmd @@ -612,6 +612,18 @@ models |> map_dbl("r.squared") ``` +Another way to obtain R squared is by using the broom package. Instead of using `split()` from base R, you can use `nest()` from tidyr: + +```{r} +mtcars |> + nest(data = -cyl) |> + arrange(cyl) |> + mutate(mod = map(data, ~lm(mpg ~ wt, data = .)), + glanced = map(mod, broom::glance)) |> + unnest(glanced) %>% + pull(r.squared) +``` + You can also use an integer to select elements by position: ```{r} @@ -705,7 +717,7 @@ str(safe_log("a")) When the function succeeds, the `result` element contains the result and the `error` element is `NULL`. When the function fails, the `result` element is `NULL` and the `error` element contains an error object. -`safely()` is designed to work with map: +`safely()` is designed to work with `map()`: ```{r} x <- list(1, 10, "a")