--- title: "Examples - Using pivot_longer() and pivot_wider()" output: word_document: default pdf_document: default html_notebook: default --- # Example of *tibble()* and *tribble()* functions to create a data_frame. ```{r message=FALSE} library(tidyverse) BP_narrow <- tibble( x = c("a", "b"), y = c(1,2), z = c(3.6, 8.5) ) BP_narrow <- tribble( ~x, ~y, ~z, "a", 2, 3.6, "b", 1, 8.5 ) ``` ```{r} BP_narrow <- tribble( ~subject, ~when, ~spb, "BHO", "before", 160, "GWB", "before", 120, "WJC", "before", 105, "BHO", "after", 115, "GWB", "after", 135, "WJC", "after", 145 ) ``` # Examples of *pivot_longer()* and *pivot_wider()* ```{r} BP_wide <- BP_narrow %>% pivot_wider(names_from = "when", values_from = "spb") BP_wide ``` ```{r} BP_narrow_new <- BP_wide %>% pivot_longer(c("before", "after"), names_to = "when", values_to = "spb" ) BP_narrow_new ``` Or we can remove the *subject* column and use the remaining two columns *before* and *after*. ```{r} BP_narrow_new <- BP_wide %>% pivot_longer(-subject, names_to = "when", values_to = "spb" ) BP_narrow_new ``` # Example *spread()* Try the code in Section 5.2.4 on pages 101-103. Try to use the new *pivot_wider()* function. ```{r} library(babynames) babynames ``` # Example *for* Try the code on pages 104-105 # Example *apply()* Try the code on pages 106-107 Next week we will take a look at the *map* functions from the *purrr* R package, which are modern alternatives to *for* loops and the *apply()* functions.