<- 100 # sample size
n <- seq(1,10) # means
m <- map(m,rnorm,n=n) samps
Challenge 10 Instructions
purrr
Challenge
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
<- function(x){
square return(x*x)
}
<- c(2,4,5,6)
vector1
#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.
<- c(2, 4, 5, 6)
x <- c(2, 3, 4, 5)
y
#make a power function
<- function(x, y){
to_Power 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.
<- tibble(
df_xyz 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.
<- map_dbl(
xyz_means .x = df_xyz,
.f = mean
)
xyz_means
x y z
-0.03784828 0.10114859 -0.17482569
<- read_csv("_data/eggs_tidy.csv")
eggs
eggs
<- tibble(
cat_table 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
.