Last updated: 2020-05-03

Checks: 7 0

Knit directory: 033_purrr_learning/

This reproducible R Markdown analysis was created with workflowr (version 1.6.2). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20200501) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version 9848eb4. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .Rproj.user/

Untracked files:
    Untracked:  data/gap_copy.rds
    Untracked:  data/gap_mod.rds
    Untracked:  data/gapminder_raw.csv

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/02_the-map-function.Rmd) and HTML (docs/02_the-map-function.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
html 36045e0 ogorodriguez 2020-05-01 Build site.
Rmd c243911 ogorodriguez 2020-05-01 Publish second section on map() function
html 6669613 ogorodriguez 2020-05-01 Build site.
Rmd f7b7a47 ogorodriguez 2020-05-01 Publish the initial files for

Introducing map()

Purrr’s map() function applies the same action to all elements of a list, or column of a data frame.

The naming convention of the map() functions help know beforehand what is the class of the resulting object or output.

  • map(.x, .f) is the main mapping function and returns a list
  • map_df(.x, .f) returns a data frame
  • map_dbl(.x, .f) returns a numeric (double) vector
  • map_chr(.x, .f) returns a character vector
  • map_lgl(.x, .f) returns a logical vector

map() arguemnts

The first argument of the map() function, the .x is the object we will iterate over; that is, .x is the data frame or list we will iterate over.

The second argument, the .f is the action or funcion we will do on each of the objects of our list, vector, or df.

The map() functions work nicely with the %>% and any other function of the tidyverse.

Simple repeated loop example

In short, map() is for iteration.

The first example here will map a function that adds ten to the quantities found in a simple numerica vector consistig of 5 numbers random from 1 to 100.

# Create function add_10
add_10 <- function(.x) {
  return(.x + 10)
}
# Create the vector with 5 random numbers. 
rand_5 <- round(runif(5, 1, 101), 0)
rand_5
#> [1] 93  3 78 74 38

Now let’s apply the function we just created to all the numbers in our rand_5 vector

map(rand_5, add_10)
#> [[1]]
#> [1] 103
#> 
#> [[2]]
#> [1] 13
#> 
#> [[3]]
#> [1] 88
#> 
#> [[4]]
#> [1] 84
#> 
#> [[5]]
#> [1] 48

The result obtained is a list of the numbers augmented by 10.

If we specify that we want a vector we should use map_dbl.

map_dbl(rand_5, add_10)
#> [1] 103  13  88  84  48

We can also map the results to characters

map_chr(rand_5, add_10)
#> [1] "103.000000" "13.000000"  "88.000000"  "84.000000"  "48.000000"

In order to get a data frame out of our vector rand_5 we need to get consistent column names. So the we will need to add some more things to our add_10 function.

We will create a data frame with one column having our original number and then a second column with the augmented number after adding 10.

map_df(rand_5, function(.x) {
  return(tibble(old_number = .x,
                new_number = add_10(.x)))
})
#> # A tibble: 5 x 2
#>   old_number new_number
#>        <dbl>      <dbl>
#> 1         93        103
#> 2          3         13
#> 3         78         88
#> 4         74         84
#> 5         38         48

We would obtain the same results with this.

rand_5 %>% 
  map_df(~ tibble(old_number = .,
               new_number = add_10(.)))
#> # A tibble: 5 x 2
#>   old_number new_number
#>        <dbl>      <dbl>
#> 1         93        103
#> 2          3         13
#> 3         78         88
#> 4         74         84
#> 5         38         48

In the previous two examples, the function used to call the tibble (the same as with the ~ in the second version of the example) that function is called an “anonymous” function since it was called and used only for that example. It is not saved in the system as the add_10 function is.

In the first anonymous function we used the .x argument but anything inside that parenthesis would have worked.

map_df(rand_5, function(y) {
  return(tibble(old_number = y,
                new_number = add_10(y)))
})
#> # A tibble: 5 x 2
#>   old_number new_number
#>        <dbl>      <dbl>
#> 1         93        103
#> 2          3         13
#> 3         78         88
#> 4         74         84
#> 5         38         48

The modify() function

The modify() function, unlike map(), returns the same object as the input. It loses the versatility of map() but it gives more control onto the output.

# If input is a vector.  The result is a vector
modify(rand_5, add_10)
#> [1] 103  13  88  84  48
# With map(), the default output is always a list
map(rand_5, add_10)
#> [[1]]
#> [1] 103
#> 
#> [[2]]
#> [1] 13
#> 
#> [[3]]
#> [1] 88
#> 
#> [[4]]
#> [1] 84
#> 
#> [[5]]
#> [1] 48
# If input is a df, output is a df with modify()
modify(as_tibble(rand_5), add_10)
#> # A tibble: 5 x 1
#>   value
#>   <dbl>
#> 1   103
#> 2    13
#> 3    88
#> 4    84
#> 5    48

modify() has a version called modify_if() that only applies the function to elements that satisfy a given criteria that needs to be specified by a predicate function (.p).

In this example we will return a vector converting only the values in our rand_5 vector that are greate than 50.

modify_if(.x = rand_5,
          .p = function(x) x > 50,
          .f = add_10)
#> [1] 103   3  88  84  38

The results is a vector of the same length, and the application of the adding of ten was only done to the last three elements that were greater than 50.

The dot(.) and the tilde(~)

As I tried to do in few examples above, temporary or anonymous functions can be explicitly called or can be substitued by the tilde (~). For example:

function(x) {
  x + 10
}
#> function(x) {
#>   x + 10
#> }

Is the function used to add 10 to any number or element of a vector.

The same can achieved with the following:

~ (.x + 10)
#> ~(.x + 10)

The tilde(~) indicates that an anonymous function is being called. The argument of the anonymous function is referred to using .x or simply the dot(.). Unlike normal function arguments (that can take any value or letter not necessarily the letter x, or .x), when the tilde is used the argument is always .x.

So the example to use insted of using the function add_10 would be:

rand_5 %>% 
  map_df(~ tibble(old_number = .x,
               new_number = add_10(.x)))
#> # A tibble: 5 x 2
#>   old_number new_number
#>        <dbl>      <dbl>
#> 1         93        103
#> 2          3         13
#> 3         78         88
#> 4         74         84
#> 5         38         48

Or

map(rand_5, ~ (add_10(.x)))
#> [[1]]
#> [1] 103
#> 
#> [[2]]
#> [1] 13
#> 
#> [[3]]
#> [1] 88
#> 
#> [[4]]
#> [1] 84
#> 
#> [[5]]
#> [1] 48
map_dbl(rand_5, ~ (add_10(.x)))
#> [1] 103  13  88  84  48

sessionInfo()
#> R version 3.6.1 (2019-07-05)
#> Platform: x86_64-w64-mingw32/x64 (64-bit)
#> Running under: Windows 10 x64 (build 18362)
#> 
#> Matrix products: default
#> 
#> locale:
#> [1] LC_COLLATE=Spanish_Spain.1252  LC_CTYPE=Spanish_Spain.1252   
#> [3] LC_MONETARY=Spanish_Spain.1252 LC_NUMERIC=C                  
#> [5] LC_TIME=Spanish_Spain.1252    
#> 
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> 
#> other attached packages:
#> [1] forcats_0.5.0   stringr_1.4.0   dplyr_0.8.5     purrr_0.3.3    
#> [5] readr_1.3.1     tidyr_1.0.2     tibble_3.0.0    tidyverse_1.3.0
#> [9] ggplot2_3.3.0  
#> 
#> loaded via a namespace (and not attached):
#>  [1] tidyselect_1.0.0 xfun_0.12        haven_2.2.0      lattice_0.20-40 
#>  [5] colorspace_1.4-1 vctrs_0.2.4      generics_0.0.2   htmltools_0.4.0 
#>  [9] yaml_2.2.1       utf8_1.1.4       rlang_0.4.5      later_1.0.0     
#> [13] pillar_1.4.3     glue_1.4.0       withr_2.1.2      DBI_1.1.0       
#> [17] dbplyr_1.4.2     readxl_1.3.1     modelr_0.1.6     lifecycle_0.2.0 
#> [21] cellranger_1.1.0 munsell_0.5.0    gtable_0.3.0     workflowr_1.6.2 
#> [25] rvest_0.3.5      evaluate_0.14    knitr_1.28       httpuv_1.5.2    
#> [29] fansi_0.4.0      broom_0.5.5      Rcpp_1.0.4.6     promises_1.1.0  
#> [33] scales_1.1.0     backports_1.1.6  jsonlite_1.6.1   fs_1.4.1        
#> [37] hms_0.5.3        digest_0.6.25    stringi_1.4.6    grid_3.6.1      
#> [41] rprojroot_1.3-2  cli_2.0.2        tools_3.6.1      magrittr_1.5    
#> [45] crayon_1.3.4     whisker_0.4      pkgconfig_2.0.3  ellipsis_0.3.0  
#> [49] xml2_1.3.1       reprex_0.3.0     lubridate_1.7.8  rstudioapi_0.11 
#> [53] assertthat_0.2.1 rmarkdown_2.1    httr_1.4.1       R6_2.4.1        
#> [57] nlme_3.1-144     git2r_0.26.1     compiler_3.6.1