├── docs ├── CNAME ├── _main.epub ├── _main.pdf ├── libs │ ├── gitbook-2.6.7 │ │ ├── css │ │ │ ├── fontawesome │ │ │ │ └── fontawesome-webfont.ttf │ │ │ ├── plugin-clipboard.css │ │ │ ├── plugin-table.css │ │ │ ├── plugin-search.css │ │ │ ├── plugin-bookdown.css │ │ │ └── plugin-fontsettings.css │ │ └── js │ │ │ ├── plugin-clipboard.js │ │ │ ├── jquery.highlight.js │ │ │ ├── plugin-sharing.js │ │ │ ├── plugin-fontsettings.js │ │ │ ├── plugin-bookdown.js │ │ │ ├── plugin-search.js │ │ │ └── clipboard.min.js │ ├── anchor-sections-1.0.1 │ │ ├── anchor-sections.css │ │ └── anchor-sections.js │ └── header-attrs-2.10 │ │ └── header-attrs.js ├── reference-keys.txt ├── style.css ├── 404.html ├── prerequisites.html ├── index.html ├── search_index.json ├── libraries-and-packages.html └── control-flow.html ├── .gitattributes ├── preamble.tex ├── _bookdown.yml ├── _common.R ├── r-guide.Rproj ├── book.bib ├── README.md ├── .gitignore ├── _output.yml ├── 07-libraries.Rmd ├── style.css ├── 04-control-flow.Rmd ├── 06-lists.Rmd ├── index.Rmd ├── 05-functions.Rmd ├── packages.bib ├── 03-types.Rmd ├── 01-basics.Rmd └── 02-arrays.Rmd /docs/CNAME: -------------------------------------------------------------------------------- 1 | r-guide.steveharoz.com -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /docs/_main.epub: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pietroppeter/r-guide/main/docs/_main.epub -------------------------------------------------------------------------------- /docs/_main.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pietroppeter/r-guide/main/docs/_main.pdf -------------------------------------------------------------------------------- /preamble.tex: -------------------------------------------------------------------------------- 1 | \usepackage{booktabs} 2 | \usepackage{fontspec} 3 | \setmainfont{Segoe UI} -------------------------------------------------------------------------------- /_bookdown.yml: -------------------------------------------------------------------------------- 1 | delete_merged_file: true 2 | language: 3 | ui: 4 | chapter_name: "Chapter " 5 | output_dir: "docs" 6 | before_chapter_script: "_common.R" -------------------------------------------------------------------------------- /docs/libs/gitbook-2.6.7/css/fontawesome/fontawesome-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pietroppeter/r-guide/main/docs/libs/gitbook-2.6.7/css/fontawesome/fontawesome-webfont.ttf -------------------------------------------------------------------------------- /_common.R: -------------------------------------------------------------------------------- 1 | set.seed(8675309) 2 | 3 | knitr::opts_chunk$set( 4 | class.output = "code_result", 5 | class.message = c("code_result", "message"), 6 | class.warning = c("code_result", "warning"), 7 | class.error = c("code_result", "error"), 8 | comment = "#>" 9 | ) -------------------------------------------------------------------------------- /r-guide.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: Sweave 13 | LaTeX: pdfLaTeX 14 | 15 | BuildType: Website 16 | -------------------------------------------------------------------------------- /docs/libs/anchor-sections-1.0.1/anchor-sections.css: -------------------------------------------------------------------------------- 1 | /* Styles for section anchors */ 2 | a.anchor-section {margin-left: 10px; visibility: hidden; color: inherit;} 3 | a.anchor-section::before {content: '#';} 4 | .hasAnchor:hover a.anchor-section {visibility: visible;} 5 | ul > li > .anchor-section {display: none;} 6 | -------------------------------------------------------------------------------- /book.bib: -------------------------------------------------------------------------------- 1 | @Book{xie2015, 2 | title = {Dynamic Documents with {R} and knitr}, 3 | author = {Yihui Xie}, 4 | publisher = {Chapman and Hall/CRC}, 5 | address = {Boca Raton, Florida}, 6 | year = {2015}, 7 | edition = {2nd}, 8 | note = {ISBN 978-1498716963}, 9 | url = {http://yihui.org/knitr/}, 10 | } 11 | -------------------------------------------------------------------------------- /docs/libs/gitbook-2.6.7/css/plugin-clipboard.css: -------------------------------------------------------------------------------- 1 | div.sourceCode { 2 | position: relative; 3 | } 4 | 5 | .copy-to-clipboard-button { 6 | position: absolute; 7 | right: 0; 8 | top: 0; 9 | visibility: hidden; 10 | } 11 | 12 | .copy-to-clipboard-button:focus { 13 | outline: 0; 14 | } 15 | 16 | div.sourceCode:hover > .copy-to-clipboard-button { 17 | visibility: visible; 18 | } 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Welcome! 2 | 3 | This is a minimal example of a book based on R Markdown and **bookdown** (https://github.com/rstudio/bookdown). 4 | 5 | This template provides a skeleton file structure that you can edit to create your book. 6 | 7 | The contents inside the .Rmd files provide some pointers to help you get started, but feel free to also delete the content in each file and start fresh. 8 | 9 | Additional resources: 10 | 11 | The **bookdown** book: https://bookdown.org/yihui/bookdown/ 12 | 13 | The **bookdown** package reference site: https://pkgs.rstudio.com/bookdown 14 | -------------------------------------------------------------------------------- /docs/libs/header-attrs-2.10/header-attrs.js: -------------------------------------------------------------------------------- 1 | // Pandoc 2.9 adds attributes on both header and div. We remove the former (to 2 | // be compatible with the behavior of Pandoc < 2.8). 3 | document.addEventListener('DOMContentLoaded', function(e) { 4 | var hs = document.querySelectorAll("div.section[class*='level'] > :first-child"); 5 | var i, h, a; 6 | for (i = 0; i < hs.length; i++) { 7 | h = hs[i]; 8 | if (!/^h[1-6]$/i.test(h.tagName)) continue; // it should be a header h1-h6 9 | a = h.attributes; 10 | while (a.length > 0) h.removeAttribute(a[0].name); 11 | } 12 | }); 13 | -------------------------------------------------------------------------------- /docs/libs/gitbook-2.6.7/css/plugin-table.css: -------------------------------------------------------------------------------- 1 | .book .book-body .page-wrapper .page-inner section.normal table{display:table;width:100%;border-collapse:collapse;border-spacing:0;overflow:auto}.book .book-body .page-wrapper .page-inner section.normal table td,.book .book-body .page-wrapper .page-inner section.normal table th{padding:6px 13px;border:1px solid #ddd}.book .book-body .page-wrapper .page-inner section.normal table tr{background-color:#fff;border-top:1px solid #ccc}.book .book-body .page-wrapper .page-inner section.normal table tr:nth-child(2n){background-color:#f8f8f8}.book .book-body .page-wrapper .page-inner section.normal table th{font-weight:700} 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # History files 2 | .Rhistory 3 | .Rapp.history 4 | 5 | # Session Data files 6 | .RData 7 | 8 | # Example code in package build process 9 | *-Ex.R 10 | 11 | # Output files from R CMD build 12 | /*.tar.gz 13 | 14 | # Output files from R CMD check 15 | /*.Rcheck/ 16 | 17 | # RStudio files 18 | .Rproj.user/ 19 | 20 | # produced vignettes 21 | vignettes/*.html 22 | vignettes/*.pdf 23 | 24 | # OAuth2 token, see https://github.com/hadley/httr/releases/tag/v0.3 25 | .httr-oauth 26 | 27 | # knitr and R markdown default cache directories 28 | /*_cache/ 29 | /cache/ 30 | 31 | # Temporary files created by R markdown 32 | *.utf8.md 33 | *.knit.md 34 | 35 | # Shiny token, see https://shiny.rstudio.com/articles/shinyapps.html 36 | rsconnect/ 37 | -------------------------------------------------------------------------------- /docs/libs/gitbook-2.6.7/css/plugin-search.css: -------------------------------------------------------------------------------- 1 | .book .book-summary .book-search { 2 | padding: 6px; 3 | background: transparent; 4 | position: absolute; 5 | top: -50px; 6 | left: 0px; 7 | right: 0px; 8 | transition: top 0.5s ease; 9 | } 10 | .book .book-summary .book-search input, 11 | .book .book-summary .book-search input:focus, 12 | .book .book-summary .book-search input:hover { 13 | width: 100%; 14 | background: transparent; 15 | border: 1px solid #ccc; 16 | box-shadow: none; 17 | outline: none; 18 | line-height: 22px; 19 | padding: 7px 4px; 20 | color: inherit; 21 | box-sizing: border-box; 22 | } 23 | .book.with-search .book-summary .book-search { 24 | top: 0px; 25 | } 26 | .book.with-search .book-summary ul.summary { 27 | top: 50px; 28 | } 29 | .with-search .summary li[data-level] a[href*=".html#"] { 30 | display: none; 31 | } 32 | -------------------------------------------------------------------------------- /docs/reference-keys.txt: -------------------------------------------------------------------------------- 1 | variables-math-comparisons-and-strings 2 | help 3 | assignment 4 | names-with-weird-characters 5 | console-output 6 | math 7 | comparisons 8 | boolean 9 | strings 10 | strings-with-special-characters 11 | string-concatenation 12 | arrays 13 | everything-is-an-array 14 | creation 15 | array-generators 16 | concatenation 17 | indexing 18 | sampling-from-an-array 19 | array-constants 20 | array-operations 21 | array-functions 22 | array-sorting 23 | test-membership 24 | types 25 | numbers 26 | strings-1 27 | concatenation-1 28 | dates 29 | finding-the-type-of-a-variable 30 | checking-the-type 31 | converting-and-parsing 32 | special-types 33 | na 34 | factor 35 | control-flow 36 | if 37 | while 38 | for 39 | functions 40 | parameters 41 | scope 42 | a-function-in-a-function 43 | dot-dot-dot 44 | operators 45 | lists 46 | make-a-list 47 | accessing-elements-in-a-list 48 | brackets-for-real 49 | names-and-values 50 | libraries-and-packages 51 | -------------------------------------------------------------------------------- /_output.yml: -------------------------------------------------------------------------------- 1 | bookdown::gitbook: 2 | css: style.css 3 | config: 4 | toc: 5 | before: | 6 |
  • A Succinct Intro to R
  • 7 | after: | 8 |
  • Steve Haroz CC-BY
  • 9 | sharing: false 10 | #edit: https://github.com/steveharoz/r-guide/edit/main/%s 11 | download: ["pdf"] #, "epub" 12 | bookdown::pdf_book: 13 | includes: 14 | in_header: preamble.tex 15 | latex_engine: xelatex 16 | citation_package: natbib 17 | keep_tex: yes 18 | bookdown::epub_book: default 19 | -------------------------------------------------------------------------------- /07-libraries.Rmd: -------------------------------------------------------------------------------- 1 | # Libraries and packages 2 | 3 | A library or package is a collection of variables, datasets, functions, and/or operators. 4 | 5 | It's called a "package" when being installed `install.packages("tidyverse")` and a "library" when being loaded for use `library(tidyverse)`. 6 | 7 | A library and a package are the same thing, but R people will insist there is a difference. Whenever talking to R people, you've got a 50-50 chance of getting it right. If you get it wrong, you're going to get a short lecture. Just nod, and say "yes, that makes sense, and the distinction is clearly important". If you say anything else, you'll get a much longer more boring lecture. 8 | 9 | I define these functions, so I don't have to worry about confusing the two. 10 | 11 | ```{r} 12 | install.library = install.packages 13 | package = library 14 | ``` 15 | 16 | If you only want to access one function or variable in a library without loading the whole thing, you can use `::` 17 | 18 | ```{r} 19 | dplyr::band_instruments 20 | ``` 21 | -------------------------------------------------------------------------------- /docs/libs/gitbook-2.6.7/js/plugin-clipboard.js: -------------------------------------------------------------------------------- 1 | gitbook.require(["gitbook", "jQuery"], function(gitbook, $) { 2 | 3 | var copyButton = ''; 4 | var clipboard; 5 | 6 | gitbook.events.bind("page.change", function() { 7 | 8 | if (!ClipboardJS.isSupported()) return; 9 | 10 | // the page.change event is thrown twice: before and after the page changes 11 | if (clipboard) { 12 | // clipboard is already defined 13 | // we can deduct that we are before page changes 14 | clipboard.destroy(); // destroy the previous events listeners 15 | clipboard = undefined; // reset the clipboard object 16 | return; 17 | } 18 | 19 | $(copyButton).prependTo("div.sourceCode"); 20 | 21 | clipboard = new ClipboardJS(".copy-to-clipboard-button", { 22 | text: function(trigger) { 23 | return trigger.parentNode.textContent; 24 | } 25 | }); 26 | 27 | }); 28 | 29 | }); 30 | -------------------------------------------------------------------------------- /style.css: -------------------------------------------------------------------------------- 1 | p.caption { 2 | color: #777; 3 | margin-top: 10px; 4 | } 5 | p code { 6 | white-space: inherit; 7 | } 8 | pre { 9 | word-break: normal; 10 | word-wrap: normal; 11 | } 12 | pre code { 13 | white-space: inherit; 14 | } 15 | 16 | /* Steve */ 17 | p + div.sourceCode { 18 | margin-top: -0.5em; 19 | } 20 | 21 | div.sourceCode + .code_result, div.sourceCode + .code_result + .code_result { 22 | margin-top: -1.1em !important 23 | } 24 | 25 | .code_result + p, div.sourceCode + .code_result + .code_result + p { 26 | margin-top: 1.5em !important; 27 | } 28 | 29 | 30 | .book .book-body .page-wrapper .page-inner section.normal div.sourceCode pre { 31 | border-top-left-radius: 5px; 32 | border-top-right-radius: 5px; 33 | } 34 | .book .book-body .page-wrapper .page-inner section.normal pre.code_result:not(.warning) { 35 | border-bottom-left-radius: 5px; 36 | border-bottom-right-radius: 5px; 37 | } 38 | .book .book-body .page-wrapper .page-inner section.normal pre.code_result { 39 | background: #f0f0f0; 40 | } 41 | .error, .message, .warning { 42 | 43 | } -------------------------------------------------------------------------------- /docs/style.css: -------------------------------------------------------------------------------- 1 | p.caption { 2 | color: #777; 3 | margin-top: 10px; 4 | } 5 | p code { 6 | white-space: inherit; 7 | } 8 | pre { 9 | word-break: normal; 10 | word-wrap: normal; 11 | } 12 | pre code { 13 | white-space: inherit; 14 | } 15 | 16 | /* Steve */ 17 | p + div.sourceCode { 18 | margin-top: -0.5em; 19 | } 20 | 21 | div.sourceCode + .code_result, div.sourceCode + .code_result + .code_result { 22 | margin-top: -1.1em !important 23 | } 24 | 25 | .code_result + p, div.sourceCode + .code_result + .code_result + p { 26 | margin-top: 1.5em !important; 27 | } 28 | 29 | 30 | .book .book-body .page-wrapper .page-inner section.normal div.sourceCode pre { 31 | border-top-left-radius: 5px; 32 | border-top-right-radius: 5px; 33 | } 34 | .book .book-body .page-wrapper .page-inner section.normal pre.code_result:not(.warning) { 35 | border-bottom-left-radius: 5px; 36 | border-bottom-right-radius: 5px; 37 | } 38 | .book .book-body .page-wrapper .page-inner section.normal pre.code_result { 39 | background: #f0f0f0; 40 | } 41 | .error, .message, .warning { 42 | 43 | } -------------------------------------------------------------------------------- /04-control-flow.Rmd: -------------------------------------------------------------------------------- 1 | 2 | # Control Flow 3 | 4 | R is primarily a functional language, so you often don't need control flow yourself. But if you want to, go for it. If you can write some quick code with a for loop, go for it! Tell the R bullies to fuck off. Do what feels comfortable to you. 5 | 6 | ## If 7 | 8 | Simple if 9 | ```{r} 10 | a = TRUE 11 | if (a) 12 | print("a is TRUE") 13 | 14 | # conditionally run multiple expressions 15 | if (a) { 16 | print("a is TRUE") 17 | print("a is TRUE") 18 | } 19 | ``` 20 | 21 | If Else 22 | ```{r} 23 | x = 5 24 | y = 8 25 | if (x > y) { 26 | print("x is greater than y") 27 | } else { 28 | print("x is less than or equal to y") 29 | } 30 | ``` 31 | 32 | The `ifelse` function is the way to handle vector operations. It is like a vectorized version of ` ? : ` in C or javascript. 33 | ```{r} 34 | x = 1:10 35 | ifelse(x %% 2 == 0, "even", "odd") 36 | ``` 37 | 38 | ## While 39 | 40 | ```{r} 41 | x = runif(1) 42 | while (x < 0.95) { 43 | x = runif(1) 44 | } 45 | ``` 46 | 47 | 48 | ## For 49 | 50 | For works like foreach in other languages. 51 | ```{r} 52 | a = runif(100, 1, 100) 53 | for (x in a) { 54 | if (x > 95) 55 | print(x) 56 | } 57 | ``` -------------------------------------------------------------------------------- /docs/libs/anchor-sections-1.0.1/anchor-sections.js: -------------------------------------------------------------------------------- 1 | // Anchor sections v1.0 written by Atsushi Yasumoto on Oct 3rd, 2020. 2 | document.addEventListener('DOMContentLoaded', function() { 3 | // Do nothing if AnchorJS is used 4 | if (typeof window.anchors === 'object' && anchors.hasOwnProperty('hasAnchorJSLink')) { 5 | return; 6 | } 7 | 8 | const h = document.querySelectorAll('h1, h2, h3, h4, h5, h6'); 9 | 10 | // Do nothing if sections are already anchored 11 | if (Array.from(h).some(x => x.classList.contains('hasAnchor'))) { 12 | return null; 13 | } 14 | 15 | // Use section id when pandoc runs with --section-divs 16 | const section_id = function(x) { 17 | return ((x.classList.contains('section') || (x.tagName === 'SECTION')) 18 | ? x.id : ''); 19 | }; 20 | 21 | // Add anchors 22 | h.forEach(function(x) { 23 | const id = x.id || section_id(x.parentElement); 24 | if (id === '' || x.matches(':empty')) { 25 | return null; 26 | } 27 | let anchor = document.createElement('a'); 28 | anchor.href = '#' + id; 29 | anchor.classList = ['anchor-section']; 30 | x.classList.add('hasAnchor'); 31 | x.appendChild(anchor); 32 | }); 33 | }); 34 | -------------------------------------------------------------------------------- /06-lists.Rmd: -------------------------------------------------------------------------------- 1 | 2 | # Lists 3 | 4 | A list is like an array but it can multiple types of elements. 5 | 6 | ## Make a list 7 | ```{r tidy=FALSE} 8 | x = list( 9 | a = 5, 10 | b = 2, 11 | Long_Name = 4.8, 12 | "named with spaces" = 0, 13 | 12, # not every element needs a name 14 | a = 20 # names don't have to be unique (but you really should avoid this) 15 | ) 16 | ``` 17 | 18 | 19 | ## Accessing elements in a list 20 | 21 | Get a tuple of the key and value 22 | ```{r} 23 | x['a'] # by key name 24 | x[1] # by index 25 | ``` 26 | 27 | Multiple keys 28 | ```{r} 29 | x[c('b', 'a')] # by key name 30 | x[c('b', 'a')] # by key name 31 | ``` 32 | 33 | Type the list name, then `$`, and press tab. R will pop up a list of keys to autocomplete. 34 | R uses `$` in the way that other languages use `.` 35 | ```{r} 36 | x$Long_Name 37 | ``` 38 | *Note: Only the value is returned.* 39 | 40 | 41 | ## Brackets for real 42 | 43 | Sometimes, R will return the whole list or object even though you asked for just one element. So you need to use double brackets. Why? Because R is snarky and doesn't believe you actually want what you said. So you need to use double brackets to explain to R that you're sure this is what you want. 44 | 45 | Double brackets only works for single items, not subsetting. 46 | ```{r} 47 | x[['a']] # by key name 48 | x[[1]] # by index 49 | ``` 50 | 51 | 52 | 53 | ## Names and values 54 | 55 | Use the `names()` function to get and set names. It behaves like an array. 56 | ```{r} 57 | names(x) 58 | names(x)[3] 59 | ``` 60 | 61 | You can modify names by assigning strings to the names function. This is weird. Take a minute to let it sink in. 62 | ```{r} 63 | names(x) = c("first", "second", "third", "fourth") 64 | names(x)[3] = "new name" 65 | ``` 66 | 67 | If all elements are the same type, this will get a vector of values 68 | ```{r} 69 | myList = list(a=1, b=2, c=3, d=4) 70 | as.vector(unlist(myList)) 71 | ``` -------------------------------------------------------------------------------- /index.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "A Succinct Intro to R" 3 | author: "Steve Haroz" 4 | date: "`r 2021 #Sys.Date()`" 5 | site: bookdown::bookdown_site 6 | documentclass: book 7 | # bibliography: [book.bib, packages.bib] 8 | url: http://r-guide.steveharoz.com/ 9 | # cover-image: path to the social sharing image like images/cover.jpg 10 | description: | 11 | This book is intended as a short introduction to the R language. 12 | It covers the basics of R and is intended as a prequal to analysis and visualization guides like "R for Data Science". 13 | This guide assumes you are familiar with programming concepts but want to learn the R language specifically. 14 | # link-citations: yes 15 | github-repo: steveharoz/r-guide 16 | --- 17 | 18 | # About {.unnumbered} 19 | 20 | This book is a short introduction to the R language. It covers the basics of R that are not covered by analysis and visualization guides like [R for Data Science](https://r4ds.had.co.na). Consider it a quick way to get up to speed on R before diving into the analysis and visualization aspects. 21 | 22 | This example-focused guide assumes you are familiar with programming concepts but want to learn the R language. It offers more examples than an "R cheat sheet" without the verbosity of a language spec or an introduction to programming. 23 | 24 | ## Sources of inspiration {.unlisted .unnumbered} 25 | 26 | 27 | 28 | [R for programmers](http://www.johndcook.com/R_language_for_programmers.html) 29 | 30 | ## Acknowledgements {.unlisted .unnumbered} 31 | 32 | People who have offered helpful suggestions: [\@pietroppeter](https://github.com/pietroppeter) 33 | 34 | # Prerequisites {.unnumbered} 35 | 36 | The prerequisites in [R for Data Science](https://r4ds.had.co.nz/introduction.html#prerequisites) are the same for this guide: 37 | 38 | 1. Install R for [Windows](https://cloud.r-project.org/bin/windows/base/), [Mac](https://cloud.r-project.org/bin/macosx/), or your [variant of Linux](https://cloud.r-project.org/bin/linux/). 39 | 2. Install [RStudio](https://www.rstudio.com/products/rstudio/). 40 | 3. (optional) Run RStudio, and install the tidyverse by typing the following into the RStudio console: `install.packages("tidyverse")` 41 | -------------------------------------------------------------------------------- /05-functions.Rmd: -------------------------------------------------------------------------------- 1 | 2 | # Functions 3 | 4 | Basic function 5 | ```{r} 6 | foo = function () { 7 | print("hello world") 8 | } 9 | foo() 10 | ``` 11 | *Note: in the function, you need to use `print` to output* 12 | 13 | ## Parameters 14 | 15 | Parameters and return values 16 | ```{r} 17 | addOne = function (x) { 18 | return(x + 1) 19 | } 20 | addOne(5) 21 | ``` 22 | *The syntax for return is like a function: `return(value)`* 23 | 24 | Parameter order can be arbitrary 25 | ```{r} 26 | add = function (x, y) { 27 | return(x + (y*10)) 28 | } 29 | add(x=2, y=10) 30 | add(y=10, x=2) 31 | ``` 32 | 33 | Functions are vectorized by default 34 | ```{r} 35 | addOne(1:5) 36 | ``` 37 | 38 | All parameters are pass-by-value because functions are immutable. 39 | 40 | ```{r} 41 | a = 5 42 | foo = function (a) { 43 | a = 6 44 | print(paste("Inside the function as a parameter: ", a)) 45 | } 46 | print(paste("Before the function: ", a)) 47 | foo(1) 48 | print(paste("After the function: ", a)) 49 | 50 | ``` 51 | 52 | 53 | ## Scope 54 | 55 | When you assign a value inside a function, it creates a local variable in the scope of the function. You can't access the global variable inside the function. (OK, you can, but the syntax is so obnoxious that I pretend it doesn't exist) 56 | 57 | ```{r} 58 | a = 5 59 | foo = function () { 60 | a = 6 61 | b = 100 62 | print(paste("Inside the function a =", a)) 63 | print(paste("Inside the function b =", b)) 64 | } 65 | print(paste("Before the function a =", a)) 66 | foo() 67 | print(paste("After the function a =", a)) 68 | #trying to use `b` will cause an error because it is out of scope 69 | ``` 70 | 71 | 72 | ## A function in a function 73 | 74 | Might be useful for encapsulation 75 | ```{r} 76 | foo = function (a, b) { 77 | square = function(x) { 78 | return(x ^ x) 79 | } 80 | print(c(a, b)) 81 | print(c(square(a), square(b))) 82 | } 83 | foo(1, 10) 84 | ``` 85 | 86 | 87 | ## Dot dot dot 88 | ```{r} 89 | foo = function (a, b) { 90 | return (a / b) 91 | } 92 | bar = function(a, ...) { 93 | return(foo(a, ...)) 94 | } 95 | bar(50, 10) 96 | bar(b = 10, 50) # named works too 97 | ``` 98 | 99 | ## Operators 100 | 101 | Operators like `+` or `-` or even `[` are all functions. To use them like a function, surround them with \`. 102 | 103 | ```{r} 104 | `+`(3, 4) 105 | `*`(3, 4) 106 | `[`(5:10, 2) # you don't need the close bracket (]) 107 | ``` 108 | 109 | -------------------------------------------------------------------------------- /packages.bib: -------------------------------------------------------------------------------- 1 | @Manual{R-base, 2 | title = {R: A Language and Environment for Statistical Computing}, 3 | author = {{R Core Team}}, 4 | organization = {R Foundation for Statistical Computing}, 5 | address = {Vienna, Austria}, 6 | year = {2021}, 7 | url = {https://www.R-project.org/}, 8 | } 9 | 10 | @Manual{R-bookdown, 11 | title = {bookdown: Authoring Books and Technical Documents with R Markdown}, 12 | author = {Yihui Xie}, 13 | year = {2021}, 14 | note = {R package version 0.24}, 15 | url = {https://CRAN.R-project.org/package=bookdown}, 16 | } 17 | 18 | @Manual{R-knitr, 19 | title = {knitr: A General-Purpose Package for Dynamic Report Generation in R}, 20 | author = {Yihui Xie}, 21 | year = {2021}, 22 | note = {R package version 1.33}, 23 | url = {https://yihui.org/knitr/}, 24 | } 25 | 26 | @Manual{R-rmarkdown, 27 | title = {rmarkdown: Dynamic Documents for R}, 28 | author = {JJ Allaire and Yihui Xie and Jonathan McPherson and Javier Luraschi and Kevin Ushey and Aron Atkins and Hadley Wickham and Joe Cheng and Winston Chang and Richard Iannone}, 29 | year = {2021}, 30 | note = {R package version 2.10}, 31 | url = {https://CRAN.R-project.org/package=rmarkdown}, 32 | } 33 | 34 | @Book{bookdown2016, 35 | title = {bookdown: Authoring Books and Technical Documents with {R} Markdown}, 36 | author = {Yihui Xie}, 37 | publisher = {Chapman and Hall/CRC}, 38 | address = {Boca Raton, Florida}, 39 | year = {2016}, 40 | note = {ISBN 978-1138700109}, 41 | url = {https://bookdown.org/yihui/bookdown}, 42 | } 43 | 44 | @Book{knitr2015, 45 | title = {Dynamic Documents with {R} and knitr}, 46 | author = {Yihui Xie}, 47 | publisher = {Chapman and Hall/CRC}, 48 | address = {Boca Raton, Florida}, 49 | year = {2015}, 50 | edition = {2nd}, 51 | note = {ISBN 978-1498716963}, 52 | url = {https://yihui.org/knitr/}, 53 | } 54 | 55 | @InCollection{knitr2014, 56 | booktitle = {Implementing Reproducible Computational Research}, 57 | editor = {Victoria Stodden and Friedrich Leisch and Roger D. Peng}, 58 | title = {knitr: A Comprehensive Tool for Reproducible Research in {R}}, 59 | author = {Yihui Xie}, 60 | publisher = {Chapman and Hall/CRC}, 61 | year = {2014}, 62 | note = {ISBN 978-1466561595}, 63 | url = {http://www.crcpress.com/product/isbn/9781466561595}, 64 | } 65 | 66 | @Book{rmarkdown2018, 67 | title = {R Markdown: The Definitive Guide}, 68 | author = {Yihui Xie and J.J. Allaire and Garrett Grolemund}, 69 | publisher = {Chapman and Hall/CRC}, 70 | address = {Boca Raton, Florida}, 71 | year = {2018}, 72 | note = {ISBN 9781138359338}, 73 | url = {https://bookdown.org/yihui/rmarkdown}, 74 | } 75 | 76 | @Book{rmarkdown2020, 77 | title = {R Markdown Cookbook}, 78 | author = {Yihui Xie and Christophe Dervieux and Emily Riederer}, 79 | publisher = {Chapman and Hall/CRC}, 80 | address = {Boca Raton, Florida}, 81 | year = {2020}, 82 | note = {ISBN 9780367563837}, 83 | url = {https://bookdown.org/yihui/rmarkdown-cookbook}, 84 | } 85 | 86 | -------------------------------------------------------------------------------- /docs/libs/gitbook-2.6.7/css/plugin-bookdown.css: -------------------------------------------------------------------------------- 1 | .book .book-header h1 { 2 | padding-left: 20px; 3 | padding-right: 20px; 4 | } 5 | .book .book-header.fixed { 6 | position: fixed; 7 | right: 0; 8 | top: 0; 9 | left: 0; 10 | border-bottom: 1px solid rgba(0,0,0,.07); 11 | } 12 | span.search-highlight { 13 | background-color: #ffff88; 14 | } 15 | @media (min-width: 600px) { 16 | .book.with-summary .book-header.fixed { 17 | left: 300px; 18 | } 19 | } 20 | @media (max-width: 1240px) { 21 | .book .book-body.fixed { 22 | top: 50px; 23 | } 24 | .book .book-body.fixed .body-inner { 25 | top: auto; 26 | } 27 | } 28 | @media (max-width: 600px) { 29 | .book.with-summary .book-header.fixed { 30 | left: calc(100% - 60px); 31 | min-width: 300px; 32 | } 33 | .book.with-summary .book-body { 34 | transform: none; 35 | left: calc(100% - 60px); 36 | min-width: 300px; 37 | } 38 | .book .book-body.fixed { 39 | top: 0; 40 | } 41 | } 42 | 43 | .book .book-body.fixed .body-inner { 44 | top: 50px; 45 | } 46 | .book .book-body .page-wrapper .page-inner section.normal sub, .book .book-body .page-wrapper .page-inner section.normal sup { 47 | font-size: 85%; 48 | } 49 | 50 | @media print { 51 | .book .book-summary, .book .book-body .book-header, .fa { 52 | display: none !important; 53 | } 54 | .book .book-body.fixed { 55 | left: 0px; 56 | } 57 | .book .book-body,.book .book-body .body-inner, .book.with-summary { 58 | overflow: visible !important; 59 | } 60 | } 61 | .kable_wrapper { 62 | border-spacing: 20px 0; 63 | border-collapse: separate; 64 | border: none; 65 | margin: auto; 66 | } 67 | .kable_wrapper > tbody > tr > td { 68 | vertical-align: top; 69 | } 70 | .book .book-body .page-wrapper .page-inner section.normal table tr.header { 71 | border-top-width: 2px; 72 | } 73 | .book .book-body .page-wrapper .page-inner section.normal table tr:last-child td { 74 | border-bottom-width: 2px; 75 | } 76 | .book .book-body .page-wrapper .page-inner section.normal table td, .book .book-body .page-wrapper .page-inner section.normal table th { 77 | border-left: none; 78 | border-right: none; 79 | } 80 | .book .book-body .page-wrapper .page-inner section.normal table.kable_wrapper > tbody > tr, .book .book-body .page-wrapper .page-inner section.normal table.kable_wrapper > tbody > tr > td { 81 | border-top: none; 82 | } 83 | .book .book-body .page-wrapper .page-inner section.normal table.kable_wrapper > tbody > tr:last-child > td { 84 | border-bottom: none; 85 | } 86 | 87 | div.theorem, div.lemma, div.corollary, div.proposition, div.conjecture { 88 | font-style: italic; 89 | } 90 | span.theorem, span.lemma, span.corollary, span.proposition, span.conjecture { 91 | font-style: normal; 92 | } 93 | div.proof>*:last-child:after { 94 | content: "\25a2"; 95 | float: right; 96 | } 97 | .header-section-number { 98 | padding-right: .5em; 99 | } 100 | #header .multi-author { 101 | margin: 0.5em 0 -0.5em 0; 102 | } 103 | #header .date { 104 | margin-top: 1.5em; 105 | } 106 | -------------------------------------------------------------------------------- /03-types.Rmd: -------------------------------------------------------------------------------- 1 | # Types 2 | 3 | ## Numbers 4 | 5 | R has integers but defaults all numbers to `numeric` which is a double precision float 6 | 7 | ```{r} 8 | x = 5 # no decimal but still a double 9 | y = x + 1 10 | ``` 11 | 12 | Good ol' float point comparison 13 | 14 | ```{r} 15 | x = .58 16 | y = .08 17 | x - y == 0.5 18 | round(x-y, digits=1) == round(0.5, digits=1) 19 | ``` 20 | 21 | Numeric division returns double 22 | 23 | ```{r} 24 | 9 / 2 # double 25 | 9 %/% 2 # drop the part after the decimal 26 | ``` 27 | 28 | ## Strings 29 | 30 | Single and double quotes are the same in R, but a given string needs the same in the beginning and end 31 | 32 | ```{r tidy=FALSE} 33 | "hello world" 34 | 'hello world' 35 | "single quote ' in a string" 36 | 'double quote " in a string' 37 | ``` 38 | 39 | ### Concatenation 40 | 41 | Concatenate with a space in between 42 | 43 | ```{r} 44 | paste('hello', 'world') 45 | ``` 46 | 47 | Use a difference separator 48 | 49 | ```{r} 50 | paste('hello', 'world', sep='_') 51 | ``` 52 | 53 | No separator 54 | 55 | ```{r} 56 | paste0('hello', 'world') 57 | ``` 58 | 59 | ## Dates 60 | 61 | See the [lubridate library](https://lubridate.tidyverse.org/). 62 | 63 | ## Finding the type of a variable 64 | 65 | ```{r} 66 | class(c(5, 'hi', TRUE)) 67 | ``` 68 | 69 | ## Checking the type 70 | 71 | What's the type? 72 | 73 | ```{r} 74 | class(5) 75 | ``` 76 | 77 | Remember, arrays are the same as single values. 78 | 79 | ```{r} 80 | class(1:5) 81 | ``` 82 | 83 | Test if numeric 84 | 85 | ```{r} 86 | is.numeric(5) 87 | ``` 88 | 89 | Test if string 90 | 91 | ```{r} 92 | is.character('hi') 93 | ``` 94 | 95 | Test if boolean 96 | 97 | ```{r} 98 | is.logical(TRUE) 99 | ``` 100 | 101 | ## Converting and parsing 102 | 103 | Parse or convert to numeric 104 | 105 | ```{r} 106 | as.numeric(c("5", TRUE, 1:3, "abc")) 107 | ``` 108 | 109 | To string 110 | 111 | ```{r} 112 | as.character(5) 113 | format(1/3) 114 | format(1/3 , digits = 16) 115 | as.character(TRUE) 116 | ``` 117 | 118 | Convert to boolean. Zero is false. Other numbers are true. 119 | 120 | ```{r} 121 | as.logical(0:2) 122 | ``` 123 | 124 | ## Special types 125 | 126 | ### NA 127 | 128 | Missing values are very common in datasets. 129 | 130 | ```{r} 131 | is.na(c(NA, 1, "")) 132 | ``` 133 | 134 | Any operation performed on NA will also yield NA. So, you can operate on arrays with missing values. 135 | 136 | ```{r} 137 | c(5, NA, 7) + 1 138 | ``` 139 | 140 | Be careful about aggregation functions like `min()`, `max()`, and `mean()`. To ignore NAs, use the `na.rm` parameter. 141 | 142 | ```{r} 143 | mean(c(5, NA, 7), na.rm=TRUE) 144 | ``` 145 | 146 | ### Factor 147 | 148 | A factor is like an enum in other languages. It encodes strings as integers via a dictionary. 149 | 150 | Create an array with many repeating values 151 | 152 | ```{r} 153 | data = sample(c("hello", "cruel", "world"), 12, replace=TRUE) 154 | data 155 | ``` 156 | 157 | Make it into a `factor` 158 | 159 | ```{r} 160 | data = factor(data) 161 | data 162 | ``` 163 | 164 | *Note: The values are in the order they appear in the array* 165 | 166 | The array is now an integer array with a dictionary 167 | 168 | ```{r} 169 | as.numeric(data) 170 | data[5] 171 | ``` 172 | 173 | See the different values in the array 174 | 175 | ```{r} 176 | levels(data) 177 | ``` 178 | 179 | For more info, see [forcats](https://forcats.tidyverse.org/). 180 | -------------------------------------------------------------------------------- /docs/libs/gitbook-2.6.7/js/jquery.highlight.js: -------------------------------------------------------------------------------- 1 | gitbook.require(["jQuery"], function(jQuery) { 2 | 3 | /* 4 | * jQuery Highlight plugin 5 | * 6 | * Based on highlight v3 by Johann Burkard 7 | * http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html 8 | * 9 | * Code a little bit refactored and cleaned (in my humble opinion). 10 | * Most important changes: 11 | * - has an option to highlight only entire words (wordsOnly - false by default), 12 | * - has an option to be case sensitive (caseSensitive - false by default) 13 | * - highlight element tag and class names can be specified in options 14 | * 15 | * Copyright (c) 2009 Bartek Szopka 16 | * 17 | * Licensed under MIT license. 18 | * 19 | */ 20 | 21 | jQuery.extend({ 22 | highlight: function (node, re, nodeName, className) { 23 | if (node.nodeType === 3) { 24 | var match = node.data.match(re); 25 | if (match) { 26 | var highlight = document.createElement(nodeName || 'span'); 27 | highlight.className = className || 'highlight'; 28 | var wordNode = node.splitText(match.index); 29 | wordNode.splitText(match[0].length); 30 | var wordClone = wordNode.cloneNode(true); 31 | highlight.appendChild(wordClone); 32 | wordNode.parentNode.replaceChild(highlight, wordNode); 33 | return 1; //skip added node in parent 34 | } 35 | } else if ((node.nodeType === 1 && node.childNodes) && // only element nodes that have children 36 | !/(script|style)/i.test(node.tagName) && // ignore script and style nodes 37 | !(node.tagName === nodeName.toUpperCase() && node.className === className)) { // skip if already highlighted 38 | for (var i = 0; i < node.childNodes.length; i++) { 39 | i += jQuery.highlight(node.childNodes[i], re, nodeName, className); 40 | } 41 | } 42 | return 0; 43 | } 44 | }); 45 | 46 | jQuery.fn.unhighlight = function (options) { 47 | var settings = { className: 'highlight', element: 'span' }; 48 | jQuery.extend(settings, options); 49 | 50 | return this.find(settings.element + "." + settings.className).each(function () { 51 | var parent = this.parentNode; 52 | parent.replaceChild(this.firstChild, this); 53 | parent.normalize(); 54 | }).end(); 55 | }; 56 | 57 | jQuery.fn.highlight = function (words, options) { 58 | var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false }; 59 | jQuery.extend(settings, options); 60 | 61 | if (words.constructor === String) { 62 | words = [words]; 63 | // also match 'foo-bar' if search for 'foo bar' 64 | if (/\s/.test(words[0])) words.push(words[0].replace(/\s+/, '-')); 65 | } 66 | words = jQuery.grep(words, function(word, i){ 67 | return word !== ''; 68 | }); 69 | words = jQuery.map(words, function(word, i) { 70 | return word.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); 71 | }); 72 | if (words.length === 0) { return this; } 73 | 74 | var flag = settings.caseSensitive ? "" : "i"; 75 | var pattern = "(" + words.join("|") + ")"; 76 | if (settings.wordsOnly) { 77 | pattern = "\\b" + pattern + "\\b"; 78 | } 79 | var re = new RegExp(pattern, flag); 80 | 81 | return this.each(function () { 82 | jQuery.highlight(this, re, settings.element, settings.className); 83 | }); 84 | }; 85 | 86 | }); 87 | -------------------------------------------------------------------------------- /01-basics.Rmd: -------------------------------------------------------------------------------- 1 | # Variables, Math, Comparisons, and Strings 2 | 3 | ## Help 4 | 5 | ```{r tidy=FALSE, eval=FALSE} 6 | # Hi. This is a comment. 7 | 8 | # If you know a function's name, but not how to use it: 9 | ?t.test 10 | ``` 11 | 12 | You can also mouseover a function and press F1. 13 | 14 | If you don't know the exact name of a function or variable, you can type part of the name and press tab to autocomplete and see some info about it. 15 | 16 | ## Assignment 17 | 18 | ```{r tidy=FALSE} 19 | a = 6 20 | b = 8 21 | c = 5.44 22 | d = TRUE 23 | e = "hello world" 24 | e = 'hello world' # same as double quote 25 | ``` 26 | 27 | *Note: No semi colon or "var" needed* 28 | 29 | You'll sometimes see `a <- 6` instead of `a = 6`. Just use `=`. Some people insist on using `<-`. They are silly. 30 | 31 | ## Names with weird characters 32 | 33 | R allows names to have a `.`, and it's common in many built-in functions. For your own variables, avoid it if possible. If you want to have a space in a name, use an underscore (`_`) instead of being rediculous. 34 | 35 | *To learn how to access object members, see the* [lists chapter](lists.html#accessing-elements-in-a-list)*.* 36 | 37 | ```{r} 38 | this.is.a.variable.name = 1 39 | better_name = 2 40 | ``` 41 | 42 | You can use any weird character like a space in a variable name by surrounding the name with \`. Avoid it if you can, but sometimes it's necessary when you load data from a file. 43 | 44 | ```{r} 45 | `more than four (>4)` = 5 46 | ``` 47 | 48 | ## Console Output 49 | 50 | Print `a` in the console 51 | 52 | ```{r} 53 | a 54 | ``` 55 | 56 | *The `[1]` is output because all values are arrays.* 57 | 58 | Another option that's useful inside functions 59 | 60 | ```{r} 61 | print(a) 62 | ``` 63 | 64 | ## Math 65 | 66 | Arithmetic 67 | 68 | ```{r tidy=FALSE} 69 | z = a + b 70 | z = a - b 71 | z = a * b 72 | z = a / b 73 | z = a %/% b # Integer division 74 | z = a %% b # Note the double % for the modulo operator 75 | z = a ^ b # exponent 76 | 77 | 1 + 2 - 3 * 4 / 5 ^ 6 # Please excuse my dear aunt, Sally 78 | ``` 79 | 80 | *Note: There is no ++ or +=* 81 | 82 | Functions for floats 83 | 84 | ```{r tidy=FALSE} 85 | floor(4.82) 86 | ceiling(4.82) 87 | ``` 88 | 89 | Rounding 90 | 91 | ```{r} 92 | round(4.4) # round down 93 | round(4.6) # round up 94 | round(4.5) # round to even (down) 95 | round(5.5) # round to even (up) 96 | ``` 97 | 98 | Other basic math functions 99 | 100 | ```{r tidy=FALSE} 101 | sin(pi/2) + cos(0) # radians, not degrees 102 | log(exp(2)) # base e (like ln) is the default 103 | log(100, 10) # use base 10 104 | ``` 105 | 106 | ## Comparisons 107 | 108 | ```{r} 109 | a == b 110 | a != b 111 | a > b 112 | a < b 113 | a >= b 114 | a <= b 115 | ``` 116 | 117 | ## Boolean 118 | 119 | ```{r} 120 | TRUE & FALSE 121 | TRUE | FALSE 122 | !TRUE 123 | ``` 124 | 125 | There's `&` and `&&`. You usually want just `&`. 126 | 127 | ## Strings 128 | 129 | Strings are not arrays in R, so array techniques may not work on strings. 130 | 131 | String length 132 | 133 | ```{r} 134 | nchar('hello world') 135 | ``` 136 | 137 | Substring 138 | 139 | ```{r} 140 | substring('hello world', 2, 10) 141 | ``` 142 | 143 | Comparison 144 | 145 | ```{r tidy=FALSE} 146 | 'hello' == "hello" 147 | ``` 148 | 149 | ### Strings with special characters 150 | 151 | If you want to use special characters in a string, you need to "escape it" by adding `\` 152 | 153 | ```{r} 154 | "string with backslashes \\, double quote \", and unicode \u263A" 155 | ``` 156 | 157 | Or you can use the literal `r"(text)"` which is useful for a Windows path or regular expression 158 | 159 | ```{r} 160 | r"(c:\hello\world)" 161 | ``` 162 | 163 | ### String Concatenation 164 | 165 | Concatenate with a space in between 166 | 167 | ```{r} 168 | paste('hello', 'world') 169 | ``` 170 | 171 | Use a difference separator 172 | 173 | ```{r} 174 | paste('hello', 'world', sep='_') 175 | ``` 176 | 177 | No separator 178 | 179 | ```{r} 180 | paste('hello', 'world', sep='') 181 | ``` 182 | -------------------------------------------------------------------------------- /docs/libs/gitbook-2.6.7/js/plugin-sharing.js: -------------------------------------------------------------------------------- 1 | gitbook.require(["gitbook", "lodash", "jQuery"], function(gitbook, _, $) { 2 | var SITES = { 3 | 'github': { 4 | 'label': 'Github', 5 | 'icon': 'fa fa-github', 6 | 'onClick': function(e) { 7 | e.preventDefault(); 8 | var repo = $('meta[name="github-repo"]').attr('content'); 9 | if (typeof repo === 'undefined') throw("Github repo not defined"); 10 | window.open("https://github.com/"+repo); 11 | } 12 | }, 13 | 'facebook': { 14 | 'label': 'Facebook', 15 | 'icon': 'fa fa-facebook', 16 | 'onClick': function(e) { 17 | e.preventDefault(); 18 | window.open("http://www.facebook.com/sharer/sharer.php?u="+encodeURIComponent(location.href)); 19 | } 20 | }, 21 | 'twitter': { 22 | 'label': 'Twitter', 23 | 'icon': 'fa fa-twitter', 24 | 'onClick': function(e) { 25 | e.preventDefault(); 26 | window.open("http://twitter.com/intent/tweet?text="+encodeURIComponent(document.title)+"&url="+encodeURIComponent(location.href)+"&hashtags=rmarkdown,bookdown"); 27 | } 28 | }, 29 | 'linkedin': { 30 | 'label': 'LinkedIn', 31 | 'icon': 'fa fa-linkedin', 32 | 'onClick': function(e) { 33 | e.preventDefault(); 34 | window.open("https://www.linkedin.com/shareArticle?mini=true&url="+encodeURIComponent(location.href)+"&title="+encodeURIComponent(document.title)); 35 | } 36 | }, 37 | 'weibo': { 38 | 'label': 'Weibo', 39 | 'icon': 'fa fa-weibo', 40 | 'onClick': function(e) { 41 | e.preventDefault(); 42 | window.open("http://service.weibo.com/share/share.php?content=utf-8&url="+encodeURIComponent(location.href)+"&title="+encodeURIComponent(document.title)); 43 | } 44 | }, 45 | 'instapaper': { 46 | 'label': 'Instapaper', 47 | 'icon': 'fa fa-italic', 48 | 'onClick': function(e) { 49 | e.preventDefault(); 50 | window.open("http://www.instapaper.com/text?u="+encodeURIComponent(location.href)); 51 | } 52 | }, 53 | 'vk': { 54 | 'label': 'VK', 55 | 'icon': 'fa fa-vk', 56 | 'onClick': function(e) { 57 | e.preventDefault(); 58 | window.open("http://vkontakte.ru/share.php?url="+encodeURIComponent(location.href)); 59 | } 60 | }, 61 | 'whatsapp': { 62 | 'label': 'Whatsapp', 63 | 'icon': 'fa fa-whatsapp', 64 | 'onClick': function(e) { 65 | e.preventDefault(); 66 | var url = encodeURIComponent(location.href); 67 | window.open((isMobile() ? "whatsapp://send" : "https://web.whatsapp.com/send") + "?text=" + url); 68 | } 69 | }, 70 | }; 71 | 72 | function isMobile() { 73 | return !!navigator.maxTouchPoints; 74 | } 75 | 76 | gitbook.events.bind("start", function(e, config) { 77 | var opts = config.sharing; 78 | if (!opts) return; 79 | 80 | // Create dropdown menu 81 | var menu = _.chain(opts.all) 82 | .map(function(id) { 83 | var site = SITES[id]; 84 | if (!site) return; 85 | return { 86 | text: site.label, 87 | onClick: site.onClick 88 | }; 89 | }) 90 | .compact() 91 | .value(); 92 | 93 | // Create main button with dropdown 94 | if (menu.length > 0) { 95 | gitbook.toolbar.createButton({ 96 | icon: 'fa fa-share-alt', 97 | label: 'Share', 98 | position: 'right', 99 | dropdown: [menu] 100 | }); 101 | } 102 | 103 | // Direct actions to share 104 | _.each(SITES, function(site, sideId) { 105 | if (!opts[sideId]) return; 106 | 107 | gitbook.toolbar.createButton({ 108 | icon: site.icon, 109 | label: site.label, 110 | title: site.label, 111 | position: 'right', 112 | onClick: site.onClick 113 | }); 114 | }); 115 | }); 116 | }); 117 | -------------------------------------------------------------------------------- /02-arrays.Rmd: -------------------------------------------------------------------------------- 1 | # Arrays 2 | 3 | In R, arrays are commonly called "vectors". R likes to be special. 4 | 5 | ## Everything is an array 6 | 7 | In R, even single values are arrays. That's why you see `[1]` in front of results: even single values are the first item in an array of length one. 8 | 9 | ## Creation 10 | 11 | `c()` is some sort of legacy nonsense from the S language. I think it means *character array* even though it can hold things other than characters. 12 | 13 | I pronounce it "CAW". Like the sound a crow makes. 14 | 15 | Simple array 16 | 17 | ```{r} 18 | c(8, 6, 7, 5) 19 | ``` 20 | 21 | For multiple types, R converts elements to the most complex type (usually a strong). For a real multi-typed collection, see [lists](lists.html) 22 | 23 | ```{r} 24 | c(9, 'hello', 7) 25 | ``` 26 | 27 | ## Array generators 28 | 29 | R has a cultural fear of complete words. Many terms are shortcuts or acronyms. 30 | 31 | Repeat 32 | 33 | ```{r} 34 | rep(0, 4) 35 | rep(c(1,2,3), 4) # repeate the whole array 36 | rep(c(1,2,3), each=4) # repeat each item in the array before moving to the next 37 | ``` 38 | 39 | Sequence 40 | 41 | ```{r} 42 | #increment by 1 43 | 4:10 44 | #increment by any other value 45 | seq(from=10, to=50, by=5) 46 | ``` 47 | 48 | Randomly sample from a given distribution 49 | 50 | ```{r} 51 | # uniform distribution (not 'run if') 52 | runif(n=5, min=0, max=1) 53 | # normal distribution 54 | rnorm(n=5, mean=0, sd=1) 55 | ``` 56 | 57 | ## Concatenation 58 | 59 | An array made up of smaller arrays combines them. R doesn't seem to allow for an array of arrays. 60 | 61 | ```{r} 62 | x = 1:3 63 | y = c(10, 11) 64 | z = 500 65 | 66 | c(x, y, z) 67 | ``` 68 | 69 | *Note: `z` is technically an array of length 1* 70 | 71 | Collapse an array into a string 72 | 73 | ```{r} 74 | paste(1:5, collapse=", ") 75 | ``` 76 | 77 | ## Indexing 78 | 79 | ```{r} 80 | a = 10:20 81 | ``` 82 | 83 | Get the first value - **Indices start at 1, not 0** 84 | 85 | ```{r} 86 | a[1] 87 | ``` 88 | 89 | 2nd and 6th values 90 | 91 | ```{r} 92 | a[c(2,6)] 93 | ``` 94 | 95 | Exclude the 2nd and 6th values 96 | 97 | ```{r} 98 | a[c(-2,-6)] 99 | ``` 100 | 101 | Range of values 102 | 103 | ```{r} 104 | a[2:6] 105 | ``` 106 | 107 | Any order or number of repetitions 108 | 109 | ```{r} 110 | a[c(2, 4, 6, 6, 6)] 111 | ``` 112 | 113 | specify values using booleans (keep this in mind for the "Array operators" section) 114 | 115 | ```{r} 116 | a[c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE)] 117 | ``` 118 | 119 | ## Sampling from an Array 120 | 121 | Randomly sample from an array. Elements may repeat. 122 | 123 | ```{r} 124 | sample(1:3, size=10, replace=TRUE) 125 | ``` 126 | 127 | *`replace` means "sample with replacement", so an element can be sampled more than once* 128 | 129 | Sample without replacement. Elements will not repeat. 130 | 131 | ```{r} 132 | sample(1:5, size=4, replace=FALSE) 133 | ``` 134 | 135 | Shuffle the order of an array 136 | 137 | ```{r} 138 | sample(a, size=length(a), replace=FALSE) 139 | ``` 140 | 141 | Make sure you have enough elements 142 | 143 | ```{r, error=TRUE} 144 | sample(1:5, size=10, replace=FALSE) 145 | ``` 146 | 147 | ## Array constants 148 | 149 | The `letters` and `LETTERS` constants hold lower and upper case letters 150 | 151 | ```{r} 152 | letters[1:5] 153 | LETTERS[1:5] 154 | ``` 155 | 156 | ## Array operations 157 | 158 | Compare individual elements 159 | 160 | ```{r} 161 | a > 15 162 | ``` 163 | 164 | Compare each element across arrays 165 | 166 | ```{r} 167 | a == c(10, 9, 12, 13, 14, 15, 16, 17, 18, 19, 20) 168 | ``` 169 | 170 | Select elements using boolean array 171 | 172 | ```{r} 173 | a[a>15] 174 | ``` 175 | 176 | You can perform operations on the elements of two arrays **even if they are different sizes**. The smaller one wraps around. 177 | 178 | ```{r} 179 | a = 1:5 180 | b = rep(1, 8) 181 | a + b 182 | ``` 183 | 184 | Because all variables are arrays, scalars work the same way: 185 | 186 | ```{r} 187 | a + 1 188 | ``` 189 | 190 | ## Array functions 191 | 192 | Length 193 | 194 | ```{r} 195 | length(20:50) 196 | ``` 197 | 198 | Reverse 199 | 200 | ```{r} 201 | rev(1:5) 202 | ``` 203 | 204 | Math 205 | 206 | ```{r} 207 | min(1:5) 208 | max(1:5) 209 | sum(1:5) 210 | ``` 211 | 212 | ## Array sorting 213 | 214 | Sort 215 | 216 | ```{r} 217 | a = c(70, 20, 80, 20, 10, 40) 218 | sort(a) 219 | ``` 220 | 221 | Reverse 222 | 223 | ```{r} 224 | sort(a, decreasing=TRUE) 225 | ``` 226 | 227 | Get the indices of the sorted values 228 | 229 | ```{r} 230 | order(a) 231 | ``` 232 | 233 | ## Test membership 234 | 235 | To see if an item is in an array, use `%in%` 236 | 237 | ```{r} 238 | 9 %in% 1:10 239 | 9:11 %in% 1:10 240 | ``` 241 | -------------------------------------------------------------------------------- /docs/libs/gitbook-2.6.7/js/plugin-fontsettings.js: -------------------------------------------------------------------------------- 1 | gitbook.require(["gitbook", "lodash", "jQuery"], function(gitbook, _, $) { 2 | var fontState; 3 | 4 | var THEMES = { 5 | "white": 0, 6 | "sepia": 1, 7 | "night": 2 8 | }; 9 | 10 | var FAMILY = { 11 | "serif": 0, 12 | "sans": 1 13 | }; 14 | 15 | // Save current font settings 16 | function saveFontSettings() { 17 | gitbook.storage.set("fontState", fontState); 18 | update(); 19 | } 20 | 21 | // Increase font size 22 | function enlargeFontSize(e) { 23 | e.preventDefault(); 24 | if (fontState.size >= 4) return; 25 | 26 | fontState.size++; 27 | saveFontSettings(); 28 | }; 29 | 30 | // Decrease font size 31 | function reduceFontSize(e) { 32 | e.preventDefault(); 33 | if (fontState.size <= 0) return; 34 | 35 | fontState.size--; 36 | saveFontSettings(); 37 | }; 38 | 39 | // Change font family 40 | function changeFontFamily(index, e) { 41 | e.preventDefault(); 42 | 43 | fontState.family = index; 44 | saveFontSettings(); 45 | }; 46 | 47 | // Change type of color 48 | function changeColorTheme(index, e) { 49 | e.preventDefault(); 50 | 51 | var $book = $(".book"); 52 | 53 | if (fontState.theme !== 0) 54 | $book.removeClass("color-theme-"+fontState.theme); 55 | 56 | fontState.theme = index; 57 | if (fontState.theme !== 0) 58 | $book.addClass("color-theme-"+fontState.theme); 59 | 60 | saveFontSettings(); 61 | }; 62 | 63 | function update() { 64 | var $book = gitbook.state.$book; 65 | 66 | $(".font-settings .font-family-list li").removeClass("active"); 67 | $(".font-settings .font-family-list li:nth-child("+(fontState.family+1)+")").addClass("active"); 68 | 69 | $book[0].className = $book[0].className.replace(/\bfont-\S+/g, ''); 70 | $book.addClass("font-size-"+fontState.size); 71 | $book.addClass("font-family-"+fontState.family); 72 | 73 | if(fontState.theme !== 0) { 74 | $book[0].className = $book[0].className.replace(/\bcolor-theme-\S+/g, ''); 75 | $book.addClass("color-theme-"+fontState.theme); 76 | } 77 | }; 78 | 79 | function init(config) { 80 | var $bookBody, $book; 81 | 82 | //Find DOM elements. 83 | $book = gitbook.state.$book; 84 | $bookBody = $book.find(".book-body"); 85 | 86 | // Instantiate font state object 87 | fontState = gitbook.storage.get("fontState", { 88 | size: config.size || 2, 89 | family: FAMILY[config.family || "sans"], 90 | theme: THEMES[config.theme || "white"] 91 | }); 92 | 93 | update(); 94 | }; 95 | 96 | 97 | gitbook.events.bind("start", function(e, config) { 98 | var opts = config.fontsettings; 99 | if (!opts) return; 100 | 101 | // Create buttons in toolbar 102 | gitbook.toolbar.createButton({ 103 | icon: 'fa fa-font', 104 | label: 'Font Settings', 105 | className: 'font-settings', 106 | dropdown: [ 107 | [ 108 | { 109 | text: 'A', 110 | className: 'font-reduce', 111 | onClick: reduceFontSize 112 | }, 113 | { 114 | text: 'A', 115 | className: 'font-enlarge', 116 | onClick: enlargeFontSize 117 | } 118 | ], 119 | [ 120 | { 121 | text: 'Serif', 122 | onClick: _.partial(changeFontFamily, 0) 123 | }, 124 | { 125 | text: 'Sans', 126 | onClick: _.partial(changeFontFamily, 1) 127 | } 128 | ], 129 | [ 130 | { 131 | text: 'White', 132 | onClick: _.partial(changeColorTheme, 0) 133 | }, 134 | { 135 | text: 'Sepia', 136 | onClick: _.partial(changeColorTheme, 1) 137 | }, 138 | { 139 | text: 'Night', 140 | onClick: _.partial(changeColorTheme, 2) 141 | } 142 | ] 143 | ] 144 | }); 145 | 146 | 147 | // Init current settings 148 | init(opts); 149 | }); 150 | }); 151 | 152 | 153 | -------------------------------------------------------------------------------- /docs/libs/gitbook-2.6.7/js/plugin-bookdown.js: -------------------------------------------------------------------------------- 1 | gitbook.require(["gitbook", "lodash", "jQuery"], function(gitbook, _, $) { 2 | 3 | var gs = gitbook.storage; 4 | 5 | gitbook.events.bind("start", function(e, config) { 6 | 7 | // add the Edit button (edit on Github) 8 | var edit = config.edit; 9 | if (edit && edit.link) gitbook.toolbar.createButton({ 10 | icon: 'fa fa-edit', 11 | label: edit.text || 'Edit', 12 | position: 'left', 13 | onClick: function(e) { 14 | e.preventDefault(); 15 | window.open(edit.link); 16 | } 17 | }); 18 | 19 | // add the History button (file history on Github) 20 | var history = config.history; 21 | if (history && history.link) gitbook.toolbar.createButton({ 22 | icon: 'fa fa-history', 23 | label: history.text || 'History', 24 | position: 'left', 25 | onClick: function(e) { 26 | e.preventDefault(); 27 | window.open(history.link); 28 | } 29 | }); 30 | 31 | // add the View button (file view on Github) 32 | var view = config.view; 33 | if (view && view.link) gitbook.toolbar.createButton({ 34 | icon: 'fa fa-eye', 35 | label: view.text || 'View Source', 36 | position: 'left', 37 | onClick: function(e) { 38 | e.preventDefault(); 39 | window.open(view.link); 40 | } 41 | }); 42 | 43 | // add the Download button 44 | var down = config.download; 45 | var normalizeDownload = function() { 46 | if (!down || !(down instanceof Array) || down.length === 0) return; 47 | if (down[0] instanceof Array) return down; 48 | return $.map(down, function(file, i) { 49 | return [[file, file.replace(/.*[.]/g, '').toUpperCase()]]; 50 | }); 51 | }; 52 | down = normalizeDownload(down); 53 | if (down) if (down.length === 1 && /[.]pdf$/.test(down[0][0])) { 54 | gitbook.toolbar.createButton({ 55 | icon: 'fa fa-file-pdf-o', 56 | label: down[0][1], 57 | position: 'left', 58 | onClick: function(e) { 59 | e.preventDefault(); 60 | window.open(down[0][0]); 61 | } 62 | }); 63 | } else { 64 | gitbook.toolbar.createButton({ 65 | icon: 'fa fa-download', 66 | label: 'Download', 67 | position: 'left', 68 | dropdown: $.map(down, function(item, i) { 69 | return { 70 | text: item[1], 71 | onClick: function(e) { 72 | e.preventDefault(); 73 | window.open(item[0]); 74 | } 75 | }; 76 | }) 77 | }); 78 | } 79 | 80 | // add the Information button 81 | var info = ['Keyboard shortcuts (<> indicates arrow keys):', 82 | '/: navigate to previous/next page', 83 | 's: Toggle sidebar']; 84 | if (config.search !== false) info.push('f: Toggle search input ' + 85 | '(use //Enter in the search input to navigate through search matches; ' + 86 | 'press Esc to cancel search)'); 87 | if (config.info !== false) gitbook.toolbar.createButton({ 88 | icon: 'fa fa-info', 89 | label: 'Information about the toolbar', 90 | position: 'left', 91 | onClick: function(e) { 92 | e.preventDefault(); 93 | window.alert(info.join('\n\n')); 94 | } 95 | }); 96 | 97 | // highlight the current section in TOC 98 | var href = window.location.pathname; 99 | href = href.substr(href.lastIndexOf('/') + 1); 100 | // accentuated characters need to be decoded (#819) 101 | href = decodeURIComponent(href); 102 | if (href === '') href = 'index.html'; 103 | var li = $('a[href^="' + href + location.hash + '"]').parent('li.chapter').first(); 104 | var summary = $('ul.summary'), chaps = summary.find('li.chapter'); 105 | if (li.length === 0) li = chaps.first(); 106 | li.addClass('active'); 107 | chaps.on('click', function(e) { 108 | chaps.removeClass('active'); 109 | $(this).addClass('active'); 110 | gs.set('tocScrollTop', summary.scrollTop()); 111 | }); 112 | 113 | var toc = config.toc; 114 | // collapse TOC items that are not for the current chapter 115 | if (toc && toc.collapse) (function() { 116 | var type = toc.collapse; 117 | if (type === 'none') return; 118 | if (type !== 'section' && type !== 'subsection') return; 119 | // sections under chapters 120 | var toc_sub = summary.children('li[data-level]').children('ul'); 121 | if (type === 'section') { 122 | toc_sub.hide() 123 | .parent().has(li).children('ul').show(); 124 | } else { 125 | toc_sub.children('li').children('ul').hide() 126 | .parent().has(li).children('ul').show(); 127 | } 128 | li.children('ul').show(); 129 | var toc_sub2 = toc_sub.children('li'); 130 | if (type === 'section') toc_sub2.children('ul').hide(); 131 | summary.children('li[data-level]').find('a') 132 | .on('click.bookdown', function(e) { 133 | if (href === $(this).attr('href').replace(/#.*/, '')) 134 | $(this).parent('li').children('ul').toggle(); 135 | }); 136 | })(); 137 | 138 | // add tooltips to the 's that are truncated 139 | $('a').each(function(i, el) { 140 | if (el.offsetWidth >= el.scrollWidth) return; 141 | if (typeof el.title === 'undefined') return; 142 | el.title = el.text; 143 | }); 144 | 145 | // restore TOC scroll position 146 | var pos = gs.get('tocScrollTop'); 147 | if (typeof pos !== 'undefined') summary.scrollTop(pos); 148 | 149 | // highlight the TOC item that has same text as the heading in view as scrolling 150 | if (toc && toc.scroll_highlight !== false && li.length > 0) (function() { 151 | // scroll the current TOC item into viewport 152 | var ht = $(window).height(), rect = li[0].getBoundingClientRect(); 153 | if (rect.top >= ht || rect.top <= 0 || rect.bottom <= 0) { 154 | summary.scrollTop(li[0].offsetTop); 155 | } 156 | // current chapter TOC items 157 | var items = $('a[href^="' + href + '"]').parent('li.chapter'), 158 | m = items.length; 159 | if (m === 0) { 160 | items = summary.find('li.chapter'); 161 | m = items.length; 162 | } 163 | if (m === 0) return; 164 | // all section titles on current page 165 | var hs = bookInner.find('.page-inner').find('h1,h2,h3'), n = hs.length, 166 | ts = hs.map(function(i, el) { return $(el).text(); }); 167 | if (n === 0) return; 168 | var scrollHandler = function(e) { 169 | var ht = $(window).height(); 170 | clearTimeout($.data(this, 'scrollTimer')); 171 | $.data(this, 'scrollTimer', setTimeout(function() { 172 | // find the first visible title in the viewport 173 | for (var i = 0; i < n; i++) { 174 | var rect = hs[i].getBoundingClientRect(); 175 | if (rect.top >= 0 && rect.bottom <= ht) break; 176 | } 177 | if (i === n) return; 178 | items.removeClass('active'); 179 | for (var j = 0; j < m; j++) { 180 | if (items.eq(j).children('a').first().text() === ts[i]) break; 181 | } 182 | if (j === m) j = 0; // highlight the chapter title 183 | // search bottom-up for a visible TOC item to highlight; if an item is 184 | // hidden, we check if its parent is visible, and so on 185 | while (j > 0 && items.eq(j).is(':hidden')) j--; 186 | items.eq(j).addClass('active'); 187 | }, 250)); 188 | }; 189 | bookInner.on('scroll.bookdown', scrollHandler); 190 | bookBody.on('scroll.bookdown', scrollHandler); 191 | })(); 192 | 193 | // do not refresh the page if the TOC item points to the current page 194 | $('a[href="' + href + '"]').parent('li.chapter').children('a') 195 | .on('click', function(e) { 196 | bookInner.scrollTop(0); 197 | bookBody.scrollTop(0); 198 | return false; 199 | }); 200 | 201 | var toolbar = config.toolbar; 202 | if (!toolbar || toolbar.position !== 'static') { 203 | var bookHeader = $('.book-header'); 204 | bookBody.addClass('fixed'); 205 | bookHeader.addClass('fixed') 206 | .css('background-color', bookBody.css('background-color')) 207 | .on('click.bookdown', function(e) { 208 | // the theme may have changed after user clicks the theme button 209 | bookHeader.css('background-color', bookBody.css('background-color')); 210 | }); 211 | } 212 | 213 | }); 214 | 215 | gitbook.events.bind("page.change", function(e) { 216 | // store TOC scroll position 217 | var summary = $('ul.summary'); 218 | gs.set('tocScrollTop', summary.scrollTop()); 219 | }); 220 | 221 | var bookBody = $('.book-body'), bookInner = bookBody.find('.body-inner'); 222 | var chapterTitle = function() { 223 | return bookInner.find('.page-inner').find('h1,h2').first().text(); 224 | }; 225 | var saveScrollPos = function(e) { 226 | // save scroll position before page is reloaded 227 | gs.set('bodyScrollTop', { 228 | body: bookBody.scrollTop(), 229 | inner: bookInner.scrollTop(), 230 | focused: document.hasFocus(), 231 | title: chapterTitle() 232 | }); 233 | }; 234 | $(document).on('servr:reload', saveScrollPos); 235 | 236 | // check if the page is loaded in an iframe (e.g. the RStudio preview window) 237 | var inIFrame = function() { 238 | var inIframe = true; 239 | try { inIframe = window.self !== window.top; } catch (e) {} 240 | return inIframe; 241 | }; 242 | if (inIFrame()) { 243 | $(window).on('blur unload', saveScrollPos); 244 | } 245 | 246 | $(function(e) { 247 | var pos = gs.get('bodyScrollTop'); 248 | if (pos) { 249 | if (pos.title === chapterTitle()) { 250 | if (pos.body !== 0) bookBody.scrollTop(pos.body); 251 | if (pos.inner !== 0) bookInner.scrollTop(pos.inner); 252 | } 253 | } 254 | if ((pos && pos.focused) || !inIFrame()) bookInner.find('.page-wrapper').focus(); 255 | // clear book body scroll position 256 | gs.remove('bodyScrollTop'); 257 | }); 258 | 259 | }); 260 | -------------------------------------------------------------------------------- /docs/libs/gitbook-2.6.7/css/plugin-fontsettings.css: -------------------------------------------------------------------------------- 1 | /* 2 | * Theme 1 3 | */ 4 | .color-theme-1 .dropdown-menu { 5 | background-color: #111111; 6 | border-color: #7e888b; 7 | } 8 | .color-theme-1 .dropdown-menu .dropdown-caret .caret-inner { 9 | border-bottom: 9px solid #111111; 10 | } 11 | .color-theme-1 .dropdown-menu .buttons { 12 | border-color: #7e888b; 13 | } 14 | .color-theme-1 .dropdown-menu .button { 15 | color: #afa790; 16 | } 17 | .color-theme-1 .dropdown-menu .button:hover { 18 | color: #73553c; 19 | } 20 | /* 21 | * Theme 2 22 | */ 23 | .color-theme-2 .dropdown-menu { 24 | background-color: #2d3143; 25 | border-color: #272a3a; 26 | } 27 | .color-theme-2 .dropdown-menu .dropdown-caret .caret-inner { 28 | border-bottom: 9px solid #2d3143; 29 | } 30 | .color-theme-2 .dropdown-menu .buttons { 31 | border-color: #272a3a; 32 | } 33 | .color-theme-2 .dropdown-menu .button { 34 | color: #62677f; 35 | } 36 | .color-theme-2 .dropdown-menu .button:hover { 37 | color: #f4f4f5; 38 | } 39 | .book .book-header .font-settings .font-enlarge { 40 | line-height: 30px; 41 | font-size: 1.4em; 42 | } 43 | .book .book-header .font-settings .font-reduce { 44 | line-height: 30px; 45 | font-size: 1em; 46 | } 47 | 48 | /* sidebar transition background */ 49 | div.book.color-theme-1 { 50 | background: #f3eacb; 51 | } 52 | .book.color-theme-1 .book-body { 53 | color: #704214; 54 | background: #f3eacb; 55 | } 56 | .book.color-theme-1 .book-body .page-wrapper .page-inner section { 57 | background: #f3eacb; 58 | } 59 | 60 | /* sidebar transition background */ 61 | div.book.color-theme-2 { 62 | background: #1c1f2b; 63 | } 64 | 65 | .book.color-theme-2 .book-body { 66 | color: #bdcadb; 67 | background: #1c1f2b; 68 | } 69 | .book.color-theme-2 .book-body .page-wrapper .page-inner section { 70 | background: #1c1f2b; 71 | } 72 | .book.font-size-0 .book-body .page-inner section { 73 | font-size: 1.2rem; 74 | } 75 | .book.font-size-1 .book-body .page-inner section { 76 | font-size: 1.4rem; 77 | } 78 | .book.font-size-2 .book-body .page-inner section { 79 | font-size: 1.6rem; 80 | } 81 | .book.font-size-3 .book-body .page-inner section { 82 | font-size: 2.2rem; 83 | } 84 | .book.font-size-4 .book-body .page-inner section { 85 | font-size: 4rem; 86 | } 87 | .book.font-family-0 { 88 | font-family: Georgia, serif; 89 | } 90 | .book.font-family-1 { 91 | font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; 92 | } 93 | .book.color-theme-1 .book-body .page-wrapper .page-inner section.normal { 94 | color: #704214; 95 | } 96 | .book.color-theme-1 .book-body .page-wrapper .page-inner section.normal a { 97 | color: inherit; 98 | } 99 | .book.color-theme-1 .book-body .page-wrapper .page-inner section.normal h1, 100 | .book.color-theme-1 .book-body .page-wrapper .page-inner section.normal h2, 101 | .book.color-theme-1 .book-body .page-wrapper .page-inner section.normal h3, 102 | .book.color-theme-1 .book-body .page-wrapper .page-inner section.normal h4, 103 | .book.color-theme-1 .book-body .page-wrapper .page-inner section.normal h5, 104 | .book.color-theme-1 .book-body .page-wrapper .page-inner section.normal h6 { 105 | color: inherit; 106 | } 107 | .book.color-theme-1 .book-body .page-wrapper .page-inner section.normal h1, 108 | .book.color-theme-1 .book-body .page-wrapper .page-inner section.normal h2 { 109 | border-color: inherit; 110 | } 111 | .book.color-theme-1 .book-body .page-wrapper .page-inner section.normal h6 { 112 | color: inherit; 113 | } 114 | .book.color-theme-1 .book-body .page-wrapper .page-inner section.normal hr { 115 | background-color: inherit; 116 | } 117 | .book.color-theme-1 .book-body .page-wrapper .page-inner section.normal blockquote { 118 | border-color: #c4b29f; 119 | opacity: 0.9; 120 | } 121 | .book.color-theme-1 .book-body .page-wrapper .page-inner section.normal pre, 122 | .book.color-theme-1 .book-body .page-wrapper .page-inner section.normal code { 123 | background: #fdf6e3; 124 | color: #657b83; 125 | border-color: #f8df9c; 126 | } 127 | .book.color-theme-1 .book-body .page-wrapper .page-inner section.normal .highlight { 128 | background-color: inherit; 129 | } 130 | .book.color-theme-1 .book-body .page-wrapper .page-inner section.normal table th, 131 | .book.color-theme-1 .book-body .page-wrapper .page-inner section.normal table td { 132 | border-color: #f5d06c; 133 | } 134 | .book.color-theme-1 .book-body .page-wrapper .page-inner section.normal table tr { 135 | color: inherit; 136 | background-color: #fdf6e3; 137 | border-color: #444444; 138 | } 139 | .book.color-theme-1 .book-body .page-wrapper .page-inner section.normal table tr:nth-child(2n) { 140 | background-color: #fbeecb; 141 | } 142 | .book.color-theme-2 .book-body .page-wrapper .page-inner section.normal { 143 | color: #bdcadb; 144 | } 145 | .book.color-theme-2 .book-body .page-wrapper .page-inner section.normal a { 146 | color: #3eb1d0; 147 | } 148 | .book.color-theme-2 .book-body .page-wrapper .page-inner section.normal h1, 149 | .book.color-theme-2 .book-body .page-wrapper .page-inner section.normal h2, 150 | .book.color-theme-2 .book-body .page-wrapper .page-inner section.normal h3, 151 | .book.color-theme-2 .book-body .page-wrapper .page-inner section.normal h4, 152 | .book.color-theme-2 .book-body .page-wrapper .page-inner section.normal h5, 153 | .book.color-theme-2 .book-body .page-wrapper .page-inner section.normal h6 { 154 | color: #fffffa; 155 | } 156 | .book.color-theme-2 .book-body .page-wrapper .page-inner section.normal h1, 157 | .book.color-theme-2 .book-body .page-wrapper .page-inner section.normal h2 { 158 | border-color: #373b4e; 159 | } 160 | .book.color-theme-2 .book-body .page-wrapper .page-inner section.normal h6 { 161 | color: #373b4e; 162 | } 163 | .book.color-theme-2 .book-body .page-wrapper .page-inner section.normal hr { 164 | background-color: #373b4e; 165 | } 166 | .book.color-theme-2 .book-body .page-wrapper .page-inner section.normal blockquote { 167 | border-color: #373b4e; 168 | } 169 | .book.color-theme-2 .book-body .page-wrapper .page-inner section.normal pre, 170 | .book.color-theme-2 .book-body .page-wrapper .page-inner section.normal code { 171 | color: #9dbed8; 172 | background: #2d3143; 173 | border-color: #2d3143; 174 | } 175 | .book.color-theme-2 .book-body .page-wrapper .page-inner section.normal .highlight { 176 | background-color: #282a39; 177 | } 178 | .book.color-theme-2 .book-body .page-wrapper .page-inner section.normal table th, 179 | .book.color-theme-2 .book-body .page-wrapper .page-inner section.normal table td { 180 | border-color: #3b3f54; 181 | } 182 | .book.color-theme-2 .book-body .page-wrapper .page-inner section.normal table tr { 183 | color: #b6c2d2; 184 | background-color: #2d3143; 185 | border-color: #3b3f54; 186 | } 187 | .book.color-theme-2 .book-body .page-wrapper .page-inner section.normal table tr:nth-child(2n) { 188 | background-color: #35394b; 189 | } 190 | .book.color-theme-1 .book-header { 191 | color: #afa790; 192 | background: transparent; 193 | } 194 | .book.color-theme-1 .book-header .btn { 195 | color: #afa790; 196 | } 197 | .book.color-theme-1 .book-header .btn:hover { 198 | color: #73553c; 199 | background: none; 200 | } 201 | .book.color-theme-1 .book-header h1 { 202 | color: #704214; 203 | } 204 | .book.color-theme-2 .book-header { 205 | color: #7e888b; 206 | background: transparent; 207 | } 208 | .book.color-theme-2 .book-header .btn { 209 | color: #3b3f54; 210 | } 211 | .book.color-theme-2 .book-header .btn:hover { 212 | color: #fffff5; 213 | background: none; 214 | } 215 | .book.color-theme-2 .book-header h1 { 216 | color: #bdcadb; 217 | } 218 | .book.color-theme-1 .book-body .navigation { 219 | color: #afa790; 220 | } 221 | .book.color-theme-1 .book-body .navigation:hover { 222 | color: #73553c; 223 | } 224 | .book.color-theme-2 .book-body .navigation { 225 | color: #383f52; 226 | } 227 | .book.color-theme-2 .book-body .navigation:hover { 228 | color: #fffff5; 229 | } 230 | /* 231 | * Theme 1 232 | */ 233 | .book.color-theme-1 .book-summary { 234 | color: #afa790; 235 | background: #111111; 236 | border-right: 1px solid rgba(0, 0, 0, 0.07); 237 | } 238 | .book.color-theme-1 .book-summary .book-search { 239 | background: transparent; 240 | } 241 | .book.color-theme-1 .book-summary .book-search input, 242 | .book.color-theme-1 .book-summary .book-search input:focus { 243 | border: 1px solid transparent; 244 | } 245 | .book.color-theme-1 .book-summary ul.summary li.divider { 246 | background: #7e888b; 247 | box-shadow: none; 248 | } 249 | .book.color-theme-1 .book-summary ul.summary li i.fa-check { 250 | color: #33cc33; 251 | } 252 | .book.color-theme-1 .book-summary ul.summary li.done > a { 253 | color: #877f6a; 254 | } 255 | .book.color-theme-1 .book-summary ul.summary li a, 256 | .book.color-theme-1 .book-summary ul.summary li span { 257 | color: #877f6a; 258 | background: transparent; 259 | font-weight: normal; 260 | } 261 | .book.color-theme-1 .book-summary ul.summary li.active > a, 262 | .book.color-theme-1 .book-summary ul.summary li a:hover { 263 | color: #704214; 264 | background: transparent; 265 | font-weight: normal; 266 | } 267 | /* 268 | * Theme 2 269 | */ 270 | .book.color-theme-2 .book-summary { 271 | color: #bcc1d2; 272 | background: #2d3143; 273 | border-right: none; 274 | } 275 | .book.color-theme-2 .book-summary .book-search { 276 | background: transparent; 277 | } 278 | .book.color-theme-2 .book-summary .book-search input, 279 | .book.color-theme-2 .book-summary .book-search input:focus { 280 | border: 1px solid transparent; 281 | } 282 | .book.color-theme-2 .book-summary ul.summary li.divider { 283 | background: #272a3a; 284 | box-shadow: none; 285 | } 286 | .book.color-theme-2 .book-summary ul.summary li i.fa-check { 287 | color: #33cc33; 288 | } 289 | .book.color-theme-2 .book-summary ul.summary li.done > a { 290 | color: #62687f; 291 | } 292 | .book.color-theme-2 .book-summary ul.summary li a, 293 | .book.color-theme-2 .book-summary ul.summary li span { 294 | color: #c1c6d7; 295 | background: transparent; 296 | font-weight: 600; 297 | } 298 | .book.color-theme-2 .book-summary ul.summary li.active > a, 299 | .book.color-theme-2 .book-summary ul.summary li a:hover { 300 | color: #f4f4f5; 301 | background: #252737; 302 | font-weight: 600; 303 | } 304 | -------------------------------------------------------------------------------- /docs/libs/gitbook-2.6.7/js/plugin-search.js: -------------------------------------------------------------------------------- 1 | gitbook.require(["gitbook", "lodash", "jQuery"], function(gitbook, _, $) { 2 | var index = null; 3 | var fuse = null; 4 | var _search = {engine: 'lunr', opts: {}}; 5 | var $searchInput, $searchLabel, $searchForm; 6 | var $highlighted = [], hi, hiOpts = { className: 'search-highlight' }; 7 | var collapse = false, toc_visible = []; 8 | 9 | function init(config) { 10 | // Instantiate search settings 11 | _search = gitbook.storage.get("search", { 12 | engine: config.search.engine || 'lunr', 13 | opts: config.search.options || {}, 14 | }); 15 | }; 16 | 17 | // Save current search settings 18 | function saveSearchSettings() { 19 | gitbook.storage.set("search", _search); 20 | } 21 | 22 | // Use a specific index 23 | function loadIndex(data) { 24 | // [Yihui] In bookdown, I use a character matrix to store the chapter 25 | // content, and the index is dynamically built on the client side. 26 | // Gitbook prebuilds the index data instead: https://github.com/GitbookIO/plugin-search 27 | // We can certainly do that via R packages V8 and jsonlite, but let's 28 | // see how slow it really is before improving it. On the other hand, 29 | // lunr cannot handle non-English text very well, e.g. the default 30 | // tokenizer cannot deal with Chinese text, so we may want to replace 31 | // lunr with a dumb simple text matching approach. 32 | if (_search.engine === 'lunr') { 33 | index = lunr(function () { 34 | this.ref('url'); 35 | this.field('title', { boost: 10 }); 36 | this.field('body'); 37 | }); 38 | data.map(function(item) { 39 | index.add({ 40 | url: item[0], 41 | title: item[1], 42 | body: item[2] 43 | }); 44 | }); 45 | return; 46 | } 47 | fuse = new Fuse(data.map((_data => { 48 | return { 49 | url: _data[0], 50 | title: _data[1], 51 | body: _data[2] 52 | }; 53 | })), Object.assign( 54 | { 55 | includeScore: true, 56 | threshold: 0.1, 57 | ignoreLocation: true, 58 | keys: ["title", "body"] 59 | }, 60 | _search.opts 61 | )); 62 | } 63 | 64 | // Fetch the search index 65 | function fetchIndex() { 66 | return $.getJSON(gitbook.state.basePath+"/search_index.json") 67 | .then(loadIndex); // [Yihui] we need to use this object later 68 | } 69 | 70 | // Search for a term and return results 71 | function search(q) { 72 | let results = []; 73 | switch (_search.engine) { 74 | case 'fuse': 75 | if (!fuse) return; 76 | results = fuse.search(q).map(function(result) { 77 | var parts = result.item.url.split('#'); 78 | return { 79 | path: parts[0], 80 | hash: parts[1] 81 | }; 82 | }); 83 | break; 84 | case 'lunr': 85 | default: 86 | if (!index) return; 87 | results = _.chain(index.search(q)).map(function(result) { 88 | var parts = result.ref.split("#"); 89 | return { 90 | path: parts[0], 91 | hash: parts[1] 92 | }; 93 | }) 94 | .value(); 95 | } 96 | 97 | // [Yihui] Highlight the search keyword on current page 98 | $highlighted = $('.page-inner') 99 | .unhighlight(hiOpts).highlight(q, hiOpts).find('span.search-highlight'); 100 | scrollToHighlighted(0); 101 | 102 | return results; 103 | } 104 | 105 | // [Yihui] Scroll the chapter body to the i-th highlighted string 106 | function scrollToHighlighted(d) { 107 | var n = $highlighted.length; 108 | hi = hi === undefined ? 0 : hi + d; 109 | // navignate to the previous/next page in the search results if reached the top/bottom 110 | var b = hi < 0; 111 | if (d !== 0 && (b || hi >= n)) { 112 | var path = currentPath(), n2 = toc_visible.length; 113 | if (n2 === 0) return; 114 | for (var i = b ? 0 : n2; (b && i < n2) || (!b && i >= 0); i += b ? 1 : -1) { 115 | if (toc_visible.eq(i).data('path') === path) break; 116 | } 117 | i += b ? -1 : 1; 118 | if (i < 0) i = n2 - 1; 119 | if (i >= n2) i = 0; 120 | var lnk = toc_visible.eq(i).find('a[href$=".html"]'); 121 | if (lnk.length) lnk[0].click(); 122 | return; 123 | } 124 | if (n === 0) return; 125 | var $p = $highlighted.eq(hi); 126 | $p[0].scrollIntoView(); 127 | $highlighted.css('background-color', ''); 128 | // an orange background color on the current item and removed later 129 | $p.css('background-color', 'orange'); 130 | setTimeout(function() { 131 | $p.css('background-color', ''); 132 | }, 2000); 133 | } 134 | 135 | function currentPath() { 136 | var href = window.location.pathname; 137 | href = href.substr(href.lastIndexOf('/') + 1); 138 | return href === '' ? 'index.html' : href; 139 | } 140 | 141 | // Create search form 142 | function createForm(value) { 143 | if ($searchForm) $searchForm.remove(); 144 | if ($searchLabel) $searchLabel.remove(); 145 | if ($searchInput) $searchInput.remove(); 146 | 147 | $searchForm = $('
    ', { 148 | 'class': 'book-search', 149 | 'role': 'search' 150 | }); 151 | 152 | $searchLabel = $('
    138 | 139 |
    140 | 222 |
    223 | 224 |
    225 |
    226 | 231 | 232 |
    233 |
    234 | 235 |
    236 |
    237 |

    Page not found

    238 |

    The page you requested cannot be found (perhaps it was moved or renamed).

    239 |

    You may want to try searching to find the page's new location, or use 240 | the table of contents to find the page you are looking for.

    241 |
    242 |
    243 | 244 |
    245 |
    246 |
    247 | 248 | 249 |
    250 |
    251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 291 | 292 | 293 | 294 | 295 | -------------------------------------------------------------------------------- /docs/prerequisites.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Prerequisites | A Succinct Intro to R 8 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 20 | 21 | 22 | 23 | 24 | 25 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 |
    138 | 139 |
    140 | 222 |
    223 | 224 |
    225 |
    226 | 231 | 232 |
    233 |
    234 | 235 |
    236 |
    237 |

    Prerequisites

    238 |

    The prerequisites in R for Data Science are the same for this guide:

    239 |
      240 |
    1. Install R for Windows, Mac, or your variant of Linux.
    2. 241 |
    3. Install RStudio.
    4. 242 |
    5. (optional) Run RStudio, and install the tidyverse by typing the following into the RStudio console: install.packages("tidyverse")
    6. 243 |
    244 | 245 |
    246 |
    247 | 248 |
    249 |
    250 |
    251 | 252 | 253 |
    254 |
    255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 295 | 296 | 297 | 298 | 299 | -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | A Succinct Intro to R 8 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 20 | 21 | 22 | 23 | 24 | 25 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 |
    138 | 139 |
    140 | 222 |
    223 | 224 |
    225 |
    226 | 231 | 232 |
    233 |
    234 | 235 |
    236 | 241 |
    242 |

    About

    243 |

    This book is a short introduction to the R language. It covers the basics of R that are not covered by analysis and visualization guides like R for Data Science. Consider it a quick way to get up to speed on R before diving into the analysis and visualization aspects.

    244 |

    This example-focused guide assumes you are familiar with programming concepts but want to learn the R language. It offers more examples than an “R cheat sheet” without the verbosity of a language spec or an introduction to programming.

    245 |
    246 |

    Sources of inspiration

    247 |

    http://alyssafrazee.com/introducing-R.html

    248 |

    R for programmers

    249 |
    250 |
    251 |

    Acknowledgements

    252 |

    People who have offered helpful suggestions: @pietroppeter

    253 |
    254 |
    255 |
    256 | 257 |
    258 |
    259 |
    260 | 261 | 262 |
    263 |
    264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 304 | 305 | 306 | 307 | 308 | -------------------------------------------------------------------------------- /docs/search_index.json: -------------------------------------------------------------------------------- 1 | [["index.html", "A Succinct Intro to R About Sources of inspiration Acknowledgements", " A Succinct Intro to R Steve Haroz 2021 About This book is a short introduction to the R language. It covers the basics of R that are not covered by analysis and visualization guides like R for Data Science. Consider it a quick way to get up to speed on R before diving into the analysis and visualization aspects. This example-focused guide assumes you are familiar with programming concepts but want to learn the R language. It offers more examples than an R cheat sheet without the verbosity of a language spec or an introduction to programming. Sources of inspiration http://alyssafrazee.com/introducing-R.html R for programmers Acknowledgements People who have offered helpful suggestions: @pietroppeter "],["prerequisites.html", "Prerequisites", " Prerequisites The prerequisites in R for Data Science are the same for this guide: Install R for Windows, Mac, or your variant of Linux. Install RStudio. (optional) Run RStudio, and install the tidyverse by typing the following into the RStudio console: install.packages(\"tidyverse\") "],["variables-math-comparisons-and-strings.html", "Chapter 1 Variables, Math, Comparisons, and Strings 1.1 Help 1.2 Assignment 1.3 Names with weird characters 1.4 Console Output 1.5 Math 1.6 Comparisons 1.7 Boolean 1.8 Strings", " Chapter 1 Variables, Math, Comparisons, and Strings 1.1 Help # Hi. This is a comment. # If you know a function's name, but not how to use it: ?t.test You can also mouseover a function and press F1. If you dont know the exact name of a function or variable, you can type part of the name and press tab to autocomplete and see some info about it. 1.2 Assignment a = 6 b = 8 c = 5.44 d = TRUE e = "hello world" e = 'hello world' # same as double quote Note: No semi colon or var needed Youll sometimes see a <- 6 instead of a = 6. Just use =. Some people insist on using <-. They are silly. 1.3 Names with weird characters R allows names to have a ., and its common in many built-in functions. For your own variables, avoid it if possible. If you want to have a space in a name, use an underscore (_) instead of being rediculous. To learn how to access object members, see the lists chapter. this.is.a.variable.name = 1 better_name = 2 You can use any weird character like a space in a variable name by surrounding the name with `. Avoid it if you can, but sometimes its necessary when you load data from a file. `more than four (>4)` = 5 1.4 Console Output Print a in the console a #> [1] 6 The [1] is output because all values are arrays. Another option thats useful inside functions print(a) #> [1] 6 1.5 Math Arithmetic z = a + b z = a - b z = a * b z = a / b z = a %/% b # Integer division z = a %% b # Note the double % for the modulo operator z = a ^ b # exponent 1 + 2 - 3 * 4 / 5 ^ 6 # Please excuse my dear aunt, Sally #> [1] 2.999232 Note: There is no ++ or += Functions for floats floor(4.82) #> [1] 4 ceiling(4.82) #> [1] 5 Rounding round(4.4) # round down #> [1] 4 round(4.6) # round up #> [1] 5 round(4.5) # round to even (down) #> [1] 4 round(5.5) # round to even (up) #> [1] 6 Other basic math functions sin(pi/2) + cos(0) # radians, not degrees #> [1] 2 log(exp(2)) # base e (like ln) is the default #> [1] 2 log(100, 10) # use base 10 #> [1] 2 1.6 Comparisons a == b #> [1] FALSE a != b #> [1] TRUE a > b #> [1] FALSE a < b #> [1] TRUE a >= b #> [1] FALSE a <= b #> [1] TRUE 1.7 Boolean TRUE & FALSE #> [1] FALSE TRUE | FALSE #> [1] TRUE !TRUE #> [1] FALSE Theres & and &&. You usually want just &. 1.8 Strings Strings are not arrays in R, so array techniques may not work on strings. String length nchar('hello world') #> [1] 11 Substring substring('hello world', 2, 10) #> [1] "ello worl" Comparison 'hello' == "hello" #> [1] TRUE 1.8.1 Strings with special characters If you want to use special characters in a string, you need to escape it by adding \\ "string with backslashes \\\\, double quote \\", and unicode \\u263A" #> [1] "string with backslashes \\\\, double quote \\", and unicode <U+263A>" Or you can use the literal r\"(text)\" which is useful for a Windows path or regular expression r"(c:\\hello\\world)" #> [1] "c:\\\\hello\\\\world" 1.8.2 String Concatenation Concatenate with a space in between paste('hello', 'world') #> [1] "hello world" Use a difference separator paste('hello', 'world', sep='_') #> [1] "hello_world" No separator paste('hello', 'world', sep='') #> [1] "helloworld" "],["arrays.html", "Chapter 2 Arrays 2.1 Everything is an array 2.2 Creation 2.3 Array generators 2.4 Concatenation 2.5 Indexing 2.6 Sampling from an Array 2.7 Array constants 2.8 Array operations 2.9 Array functions 2.10 Array sorting 2.11 Test membership", " Chapter 2 Arrays In R, arrays are commonly called vectors. R likes to be special. 2.1 Everything is an array In R, even single values are arrays. Thats why you see [1] in front of results: even single values are the first item in an array of length one. 2.2 Creation c() is some sort of legacy nonsense from the S language. I think it means character array even though it can hold things other than characters. I pronounce it CAW. Like the sound a crow makes. Simple array c(8, 6, 7, 5) #> [1] 8 6 7 5 For multiple types, R converts elements to the most complex type (usually a strong). For a real multi-typed collection, see lists c(9, 'hello', 7) #> [1] "9" "hello" "7" 2.3 Array generators R has a cultural fear of complete words. Many terms are shortcuts or acronyms. Repeat rep(0, 4) #> [1] 0 0 0 0 rep(c(1,2,3), 4) # repeate the whole array #> [1] 1 2 3 1 2 3 1 2 3 1 2 3 rep(c(1,2,3), each=4) # repeat each item in the array before moving to the next #> [1] 1 1 1 1 2 2 2 2 3 3 3 3 Sequence #increment by 1 4:10 #> [1] 4 5 6 7 8 9 10 #increment by any other value seq(from=10, to=50, by=5) #> [1] 10 15 20 25 30 35 40 45 50 Randomly sample from a given distribution # uniform distribution (not 'run if') runif(n=5, min=0, max=1) #> [1] 0.1594836 0.4781883 0.7647987 0.7696877 0.2685485 # normal distribution rnorm(n=5, mean=0, sd=1) #> [1] 0.4483395 1.0208067 -0.1378989 0.2103863 -0.6428271 2.4 Concatenation An array made up of smaller arrays combines them. R doesnt seem to allow for an array of arrays. x = 1:3 y = c(10, 11) z = 500 c(x, y, z) #> [1] 1 2 3 10 11 500 Note: z is technically an array of length 1 Collapse an array into a string paste(1:5, collapse=", ") #> [1] "1, 2, 3, 4, 5" 2.5 Indexing a = 10:20 Get the first value - Indices start at 1, not 0 a[1] #> [1] 10 2nd and 6th values a[c(2,6)] #> [1] 11 15 Exclude the 2nd and 6th values a[c(-2,-6)] #> [1] 10 12 13 14 16 17 18 19 20 Range of values a[2:6] #> [1] 11 12 13 14 15 Any order or number of repetitions a[c(2, 4, 6, 6, 6)] #> [1] 11 13 15 15 15 specify values using booleans (keep this in mind for the Array operators section) a[c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE, FALSE)] #> [1] 10 12 14 16 18 20 2.6 Sampling from an Array Randomly sample from an array. Elements may repeat. sample(1:3, size=10, replace=TRUE) #> [1] 1 1 2 3 2 2 2 2 3 1 replace means sample with replacement, so an element can be sampled more than once Sample without replacement. Elements will not repeat. sample(1:5, size=4, replace=FALSE) #> [1] 4 3 1 5 Shuffle the order of an array sample(a, size=length(a), replace=FALSE) #> [1] 15 13 17 20 18 10 12 16 14 11 19 Make sure you have enough elements sample(1:5, size=10, replace=FALSE) #> Error in sample.int(length(x), size, replace, prob): cannot take a sample larger than the population when 'replace = FALSE' 2.7 Array constants The letters and LETTERS constants hold lower and upper case letters letters[1:5] #> [1] "a" "b" "c" "d" "e" LETTERS[1:5] #> [1] "A" "B" "C" "D" "E" 2.8 Array operations Compare individual elements a > 15 #> [1] FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE Compare each element across arrays a == c(10, 9, 12, 13, 14, 15, 16, 17, 18, 19, 20) #> [1] TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE Select elements using boolean array a[a>15] #> [1] 16 17 18 19 20 You can perform operations on the elements of two arrays even if they are different sizes. The smaller one wraps around. a = 1:5 b = rep(1, 8) a + b #> Warning in a + b: longer object length is not a multiple of shorter object #> length #> [1] 2 3 4 5 6 2 3 4 Because all variables are arrays, scalars work the same way: a + 1 #> [1] 2 3 4 5 6 2.9 Array functions Length length(20:50) #> [1] 31 Reverse rev(1:5) #> [1] 5 4 3 2 1 Math min(1:5) #> [1] 1 max(1:5) #> [1] 5 sum(1:5) #> [1] 15 2.10 Array sorting Sort a = c(70, 20, 80, 20, 10, 40) sort(a) #> [1] 10 20 20 40 70 80 Reverse sort(a, decreasing=TRUE) #> [1] 80 70 40 20 20 10 Get the indices of the sorted values order(a) #> [1] 5 2 4 6 1 3 2.11 Test membership To see if an item is in an array, use %in% 9 %in% 1:10 #> [1] TRUE 9:11 %in% 1:10 #> [1] TRUE TRUE FALSE "],["types.html", "Chapter 3 Types 3.1 Numbers 3.2 Strings 3.3 Dates 3.4 Finding the type of a variable 3.5 Checking the type 3.6 Converting and parsing 3.7 Special types", " Chapter 3 Types 3.1 Numbers R has integers but defaults all numbers to numeric which is a double precision float x = 5 # no decimal but still a double y = x + 1 Good ol float point comparison x = .58 y = .08 x - y == 0.5 #> [1] FALSE round(x-y, digits=1) == round(0.5, digits=1) #> [1] TRUE Numeric division returns double 9 / 2 # double #> [1] 4.5 9 %/% 2 # drop the part after the decimal #> [1] 4 3.2 Strings Single and double quotes are the same in R, but a given string needs the same in the beginning and end "hello world" #> [1] "hello world" 'hello world' #> [1] "hello world" "single quote ' in a string" #> [1] "single quote ' in a string" 'double quote " in a string' #> [1] "double quote \\" in a string" 3.2.1 Concatenation Concatenate with a space in between paste('hello', 'world') #> [1] "hello world" Use a difference separator paste('hello', 'world', sep='_') #> [1] "hello_world" No separator paste0('hello', 'world') #> [1] "helloworld" 3.3 Dates See the lubridate library. 3.4 Finding the type of a variable class(c(5, 'hi', TRUE)) #> [1] "character" 3.5 Checking the type Whats the type? class(5) #> [1] "numeric" Remember, arrays are the same as single values. class(1:5) #> [1] "integer" Test if numeric is.numeric(5) #> [1] TRUE Test if string is.character('hi') #> [1] TRUE Test if boolean is.logical(TRUE) #> [1] TRUE 3.6 Converting and parsing Parse or convert to numeric as.numeric(c("5", TRUE, 1:3, "abc")) #> Warning: NAs introduced by coercion #> [1] 5 NA 1 2 3 NA To string as.character(5) #> [1] "5" format(1/3) #> [1] "0.3333333" format(1/3 , digits = 16) #> [1] "0.3333333333333333" as.character(TRUE) #> [1] "TRUE" Convert to boolean. Zero is false. Other numbers are true. as.logical(0:2) #> [1] FALSE TRUE TRUE 3.7 Special types 3.7.1 NA Missing values are very common in datasets. is.na(c(NA, 1, "")) #> [1] TRUE FALSE FALSE Any operation performed on NA will also yield NA. So, you can operate on arrays with missing values. c(5, NA, 7) + 1 #> [1] 6 NA 8 Be careful about aggregation functions like min(), max(), and mean(). To ignore NAs, use the na.rm parameter. mean(c(5, NA, 7), na.rm=TRUE) #> [1] 6 3.7.2 Factor A factor is like an enum in other languages. It encodes strings as integers via a dictionary. Create an array with many repeating values data = sample(c("hello", "cruel", "world"), 12, replace=TRUE) data #> [1] "world" "cruel" "world" "hello" "world" "hello" "cruel" "world" "world" #> [10] "hello" "cruel" "world" Make it into a factor data = factor(data) data #> [1] world cruel world hello world hello cruel world world hello cruel world #> Levels: cruel hello world Note: The values are in the order they appear in the array The array is now an integer array with a dictionary as.numeric(data) #> [1] 3 1 3 2 3 2 1 3 3 2 1 3 data[5] #> [1] world #> Levels: cruel hello world See the different values in the array levels(data) #> [1] "cruel" "hello" "world" For more info, see forcats. "],["control-flow.html", "Chapter 4 Control Flow 4.1 If 4.2 While 4.3 For", " Chapter 4 Control Flow R is primarily a functional language, so you often dont need control flow yourself. But if you want to, go for it. If you can write some quick code with a for loop, go for it! Tell the R bullies to fuck off. Do what feels comfortable to you. 4.1 If Simple if a = TRUE if (a) print("a is TRUE") #> [1] "a is TRUE" # conditionally run multiple expressions if (a) { print("a is TRUE") print("a is TRUE") } #> [1] "a is TRUE" #> [1] "a is TRUE" If Else x = 5 y = 8 if (x > y) { print("x is greater than y") } else { print("x is less than or equal to y") } #> [1] "x is less than or equal to y" The ifelse function is the way to handle vector operations. It is like a vectorized version of ? : in C or javascript. x = 1:10 ifelse(x %% 2 == 0, "even", "odd") #> [1] "odd" "even" "odd" "even" "odd" "even" "odd" "even" "odd" "even" 4.2 While x = runif(1) while (x < 0.95) { x = runif(1) } 4.3 For For works like foreach in other languages. a = runif(100, 1, 100) for (x in a) { if (x > 95) print(x) } #> [1] 97.59641 #> [1] 97.67089 #> [1] 95.54705 "],["functions.html", "Chapter 5 Functions 5.1 Parameters 5.2 Scope 5.3 A function in a function 5.4 Dot dot dot 5.5 Operators", " Chapter 5 Functions Basic function foo = function () { print("hello world") } foo() #> [1] "hello world" Note: in the function, you need to use print to output 5.1 Parameters Parameters and return values addOne = function (x) { return(x + 1) } addOne(5) #> [1] 6 The syntax for return is like a function: return(value) Parameter order can be arbitrary add = function (x, y) { return(x + (y*10)) } add(x=2, y=10) #> [1] 102 add(y=10, x=2) #> [1] 102 Functions are vectorized by default addOne(1:5) #> [1] 2 3 4 5 6 All parameters are pass-by-value because functions are immutable. a = 5 foo = function (a) { a = 6 print(paste("Inside the function as a parameter: ", a)) } print(paste("Before the function: ", a)) #> [1] "Before the function: 5" foo(1) #> [1] "Inside the function as a parameter: 6" print(paste("After the function: ", a)) #> [1] "After the function: 5" 5.2 Scope When you assign a value inside a function, it creates a local variable in the scope of the function. You cant access the global variable inside the function. (OK, you can, but the syntax is so obnoxious that I pretend it doesnt exist) a = 5 foo = function () { a = 6 b = 100 print(paste("Inside the function a =", a)) print(paste("Inside the function b =", b)) } print(paste("Before the function a =", a)) #> [1] "Before the function a = 5" foo() #> [1] "Inside the function a = 6" #> [1] "Inside the function b = 100" print(paste("After the function a =", a)) #> [1] "After the function a = 5" #trying to use `b` will cause an error because it is out of scope 5.3 A function in a function Might be useful for encapsulation foo = function (a, b) { square = function(x) { return(x ^ x) } print(c(a, b)) print(c(square(a), square(b))) } foo(1, 10) #> [1] 1 10 #> [1] 1e+00 1e+10 5.4 Dot dot dot foo = function (a, b) { return (a / b) } bar = function(a, ...) { return(foo(a, ...)) } bar(50, 10) #> [1] 5 bar(b = 10, 50) # named works too #> [1] 5 5.5 Operators Operators like + or - or even [ are all functions. To use them like a function, surround them with `. `+`(3, 4) #> [1] 7 `*`(3, 4) #> [1] 12 `[`(5:10, 2) # you don't need the close bracket (]) #> [1] 6 "],["lists.html", "Chapter 6 Lists 6.1 Make a list 6.2 Accessing elements in a list 6.3 Brackets for real 6.4 Names and values", " Chapter 6 Lists A list is like an array but it can multiple types of elements. 6.1 Make a list x = list( a = 5, b = 2, Long_Name = 4.8, "named with spaces" = 0, 12, # not every element needs a name a = 20 # names don't have to be unique (but you really should avoid this) ) 6.2 Accessing elements in a list Get a tuple of the key and value x['a'] # by key name #> $a #> [1] 5 x[1] # by index #> $a #> [1] 5 Multiple keys x[c('b', 'a')] # by key name #> $b #> [1] 2 #> #> $a #> [1] 5 x[c('b', 'a')] # by key name #> $b #> [1] 2 #> #> $a #> [1] 5 Type the list name, then $, and press tab. R will pop up a list of keys to autocomplete. R uses $ in the way that other languages use . x$Long_Name #> [1] 4.8 Note: Only the value is returned. 6.3 Brackets for real Sometimes, R will return the whole list or object even though you asked for just one element. So you need to use double brackets. Why? Because R is snarky and doesnt believe you actually want what you said. So you need to use double brackets to explain to R that youre sure this is what you want. Double brackets only works for single items, not subsetting. x[['a']] # by key name #> [1] 5 x[[1]] # by index #> [1] 5 6.4 Names and values Use the names() function to get and set names. It behaves like an array. names(x) #> [1] "a" "b" "Long_Name" #> [4] "named with spaces" "" "a" names(x)[3] #> [1] "Long_Name" You can modify names by assigning strings to the names function. This is weird. Take a minute to let it sink in. names(x) = c("first", "second", "third", "fourth") names(x)[3] = "new name" If all elements are the same type, this will get a vector of values myList = list(a=1, b=2, c=3, d=4) as.vector(unlist(myList)) #> [1] 1 2 3 4 "],["libraries-and-packages.html", "Chapter 7 Libraries and packages", " Chapter 7 Libraries and packages A library or package is a collection of variables, datasets, functions, and/or operators. Its called a package when being installed install.packages(\"tidyverse\") and a library when being loaded for use library(tidyverse). A library and a package are the same thing, but R people will insist there is a difference. Whenever talking to R people, youve got a 50-50 chance of getting it right. If you get it wrong, youre going to get a short lecture. Just nod, and say yes, that makes sense, and the distinction is clearly important. If you say anything else, youll get a much longer more boring lecture. I define these functions, so I dont have to worry about confusing the two. install.library = install.packages package = library If you only want to access one function or variable in a library without loading the whole thing, you can use :: dplyr::band_instruments #> # A tibble: 3 x 2 #> name plays #> <chr> <chr> #> 1 John guitar #> 2 Paul bass #> 3 Keith guitar "],["404.html", "Page not found", " Page not found The page you requested cannot be found (perhaps it was moved or renamed). You may want to try searching to find the page's new location, or use the table of contents to find the page you are looking for. "]] 2 | -------------------------------------------------------------------------------- /docs/libraries-and-packages.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Chapter 7 Libraries and packages | A Succinct Intro to R 8 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 20 | 21 | 22 | 23 | 24 | 25 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 |
    138 | 139 |
    140 | 222 |
    223 | 224 |
    225 |
    226 | 231 | 232 |
    233 |
    234 | 235 |
    236 |
    237 |

    Chapter 7 Libraries and packages

    238 |

    A library or package is a collection of variables, datasets, functions, and/or operators.

    239 |

    It’s called a “package” when being installed install.packages("tidyverse") and a “library” when being loaded for use library(tidyverse).

    240 |

    A library and a package are the same thing, but R people will insist there is a difference. Whenever talking to R people, you’ve got a 50-50 chance of getting it right. If you get it wrong, you’re going to get a short lecture. Just nod, and say “yes, that makes sense, and the distinction is clearly important”. If you say anything else, you’ll get a much longer more boring lecture.

    241 |

    I define these functions, so I don’t have to worry about confusing the two.

    242 |
    install.library = install.packages
    243 | package = library
    244 |

    If you only want to access one function or variable in a library without loading the whole thing, you can use ::

    245 |
    dplyr::band_instruments
    246 |
    #> # A tibble: 3 x 2
    247 | #>   name  plays 
    248 | #>   <chr> <chr> 
    249 | #> 1 John  guitar
    250 | #> 2 Paul  bass  
    251 | #> 3 Keith guitar
    252 | 253 |
    254 |
    255 | 256 |
    257 |
    258 |
    259 | 260 | 261 |
    262 |
    263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 303 | 304 | 305 | 306 | 307 | -------------------------------------------------------------------------------- /docs/control-flow.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Chapter 4 Control Flow | A Succinct Intro to R 8 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 20 | 21 | 22 | 23 | 24 | 25 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 |
    138 | 139 |
    140 | 222 |
    223 | 224 |
    225 |
    226 | 231 | 232 |
    233 |
    234 | 235 |
    236 |
    237 |

    Chapter 4 Control Flow

    238 |

    R is primarily a functional language, so you often don’t need control flow yourself. But if you want to, go for it. If you can write some quick code with a for loop, go for it! Tell the R bullies to fuck off. Do what feels comfortable to you.

    239 |
    240 |

    4.1 If

    241 |

    Simple if

    242 |
    a = TRUE
    243 | if (a)  
    244 |   print("a is TRUE")
    245 |
    #> [1] "a is TRUE"
    246 |
    # conditionally run multiple expressions
    247 | if (a) {
    248 |   print("a is TRUE")
    249 |   print("a is TRUE")
    250 | }
    251 |
    #> [1] "a is TRUE"
    252 | #> [1] "a is TRUE"
    253 |

    If Else

    254 |
    x = 5
    255 | y = 8
    256 | if (x > y) {
    257 |   print("x is greater than y")
    258 | } else {
    259 |   print("x is less than or equal to y")
    260 | }
    261 |
    #> [1] "x is less than or equal to y"
    262 |

    The ifelse function is the way to handle vector operations. It is like a vectorized version of ? : in C or javascript.

    263 |
    x = 1:10
    264 | ifelse(x %% 2 == 0, "even", "odd")
    265 |
    #>  [1] "odd"  "even" "odd"  "even" "odd"  "even" "odd"  "even" "odd"  "even"
    266 |
    267 |
    268 |

    4.2 While

    269 |
    x = runif(1)
    270 | while (x < 0.95) {
    271 |   x = runif(1)
    272 | }
    273 |
    274 |
    275 |

    4.3 For

    276 |

    For works like foreach in other languages.

    277 |
    a = runif(100, 1, 100)
    278 | for (x in a) {
    279 |   if (x > 95)
    280 |     print(x)
    281 | }
    282 |
    #> [1] 97.59641
    283 | #> [1] 97.67089
    284 | #> [1] 95.54705
    285 | 286 |
    287 |
    288 |
    289 | 290 |
    291 |
    292 |
    293 | 294 | 295 |
    296 |
    297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 337 | 338 | 339 | 340 | 341 | --------------------------------------------------------------------------------