Example of tibble() and tribble() functions to create a data_frame.

library(tidyverse)
Warning message:
In scan(file = file, what = what, sep = sep, quote = quote, dec = dec,  :
  EOF within quoted string
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
)
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()

BP_wide <- BP_narrow %>% pivot_wider(names_from = "when", values_from = "spb")
BP_wide
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.

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.

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.

LS0tCnRpdGxlOiAiRXhhbXBsZXMgLSBVc2luZyBwaXZvdF9sb25nZXIoKSBhbmQgcGl2b3Rfd2lkZXIoKSIKb3V0cHV0OgogIHdvcmRfZG9jdW1lbnQ6IGRlZmF1bHQKICBwZGZfZG9jdW1lbnQ6IGRlZmF1bHQKICBodG1sX25vdGVib29rOiBkZWZhdWx0Ci0tLQoKIyBFeGFtcGxlIG9mICp0aWJibGUoKSogYW5kICp0cmliYmxlKCkqIGZ1bmN0aW9ucyB0byBjcmVhdGUgYSBkYXRhX2ZyYW1lLgoKYGBge3IgbWVzc2FnZT1GQUxTRX0KbGlicmFyeSh0aWR5dmVyc2UpCgpCUF9uYXJyb3cgPC0gdGliYmxlKAogIHggPSBjKCJhIiwgImIiKSw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