Challenge 10 Instructions

purrr
Author

Shuqi Hong

Published

July 6, 2023

Challenge

n <- 100 # sample size
m <- seq(1,10) # means 
samps <- map(m,rnorm,n=n) 

We can then use map_dbl to verify that this worked correctly by computing the mean for each sample.

samps %>%
  map_dbl(mean)
 [1]  1.008648  1.987464  2.902682  3.914654  4.980311  6.001412  7.211963
 [8]  8.064765  9.006044 10.115006

The map() is used to apply a function to each element of the list or a vector.

#the square function is to calculate x square
square <- function(x){
  return(x*x)
}

vector1 <- c(2,4,5,6)

#applay square function to vector1
map(vector1, square)
[[1]]
[1] 4

[[2]]
[1] 16

[[3]]
[1] 25

[[4]]
[1] 36

map2() is used to apply a function to a pair of elements from two different lists or vectors.

x <- c(2, 4, 5, 6)
y <- c(2, 3, 4, 5)

#make a power function
to_Power <- function(x, y){
  return(x**y)
}

#apply the to_power function to x and y
map2(x, y, to_Power)
[[1]]
[1] 4

[[2]]
[1] 64

[[3]]
[1] 625

[[4]]
[1] 7776

In this chunck, the result should be x^y.

Make a tibble here.

df_xyz <- tibble(
  x = rnorm(10),
  y = rnorm(10),
  z = rnorm(10)
) %>% 
  print()
# A tibble: 10 × 3
          x       y      z
      <dbl>   <dbl>  <dbl>
 1 -0.463    0.758   1.96 
 2 -0.563   -0.416   0.156
 3 -0.300   -0.0898 -1.58 
 4 -0.413    1.04    0.361
 5 -0.00608  0.818  -0.215
 6  0.986   -0.859  -0.380
 7  0.866    0.766  -0.457
 8 -0.340   -0.431   0.212
 9  0.314   -1.70   -1.39 
10 -0.458    1.13   -0.422

use the map_dbl() function from the purrr package to calculate the mean of each column in the df_xyz data frame.

xyz_means <- map_dbl(
  .x = df_xyz, 
  .f = mean
) 

xyz_means
          x           y           z 
-0.03784828  0.10114859 -0.17482569 
eggs <- read_csv("_data/eggs_tidy.csv")

eggs
cat_table <- tibble(
  category = vector("character"), 
  variable = vector("numeric"), 
  n        = vector("numeric")
) 

map_dfr(
  .x = c("large_half_dozen", "large_dozen", "extra_large_half_dozen","extra_large_dozen"),
  .f = function(x) {
   eggs %>% 
      count(.data[[x]]) %>% 
      mutate(category = names(.)[1]) %>% 
      rename(variable = 1) %>% 
      select(category, variable, n)
  }
)

This function looks like pivot.