From 05cbc10f7bc2658cf9625c0af4c246b1cdbc7e00 Mon Sep 17 00:00:00 2001 From: Andy Teucher Date: Thu, 1 Jun 2023 15:58:15 -0700 Subject: [PATCH] Accessibility fixes (#296) * make sure to include alt tag in decorative images * Add alt text to contributed cheatsheet thumbnails * Ignore .Rbuildignore since it's not a package * Logo alt text * Add logo alt text for data-import. * Remove from yaml header in data-visualization since they are inherited from the logo * Alt text for the rest of the posit package logos * update freeze * Add a period, formatting --- .gitignore | 2 +- .../data-import/execute-results/html.json | 8 +- .../execute-results/html.json | 4 +- .../execute-results/html.json | 4 +- .../html/factors/execute-results/html.json | 4 +- _freeze/html/keras/execute-results/html.json | 4 +- .../html/lubridate/execute-results/html.json | 4 +- .../execute-results/html.json | 4 +- .../html/plumber/execute-results/html.json | 4 +- _freeze/html/purrr/execute-results/html.json | 4 +- .../html/reticulate/execute-results/html.json | 4 +- .../html/rmarkdown/execute-results/html.json | 4 +- .../rstudio-ide/execute-results/html.json | 4 +- _freeze/html/shiny/execute-results/html.json | 4 +- .../html/strings/execute-results/html.json | 8 +- _freeze/html/tidyr/execute-results/html.json | 4 +- contributed-cheatsheets.qmd | 108 +++++++++--------- html/common.R | 4 +- html/data-import.qmd | 16 +-- html/data-transformation.qmd | 5 +- html/data-visualization.qmd | 7 +- html/factors.qmd | 5 +- html/keras.qmd | 4 +- html/lubridate.qmd | 4 +- html/package-development.qmd | 4 +- html/plumber.qmd | 7 +- html/purrr.qmd | 4 +- html/reticulate.qmd | 5 +- html/rmarkdown.qmd | 4 +- html/rstudio-ide.qmd | 5 +- html/shiny.qmd | 5 +- html/strings.qmd | 20 ++-- html/tidyr.qmd | 4 +- 33 files changed, 160 insertions(+), 121 deletions(-) diff --git a/.gitignore b/.gitignore index 0ef37710..601cb26b 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,6 @@ cheatsheets.Rproj .Rhistory .RData rsconnect/ - /.quarto/ _site +.Rbuildignore diff --git a/_freeze/html/data-import/execute-results/html.json b/_freeze/html/data-import/execute-results/html.json index 081884e5..2213be76 100644 --- a/_freeze/html/data-import/execute-results/html.json +++ b/_freeze/html/data-import/execute-results/html.json @@ -1,8 +1,10 @@ { - "hash": "d0c74b98b35b5ef1a46c33388e87a664", + "hash": "17bdd6c7cb248715e8d4f870441606fe", "result": { - "markdown": "---\ntitle: \"Data import with the tidyverse :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: true\n---\n\n::: {.cell .column-margin}\n\"\"\n

\n

Download PDF

\n\n
\n

Translations (PDF)

\n* Bengali\n* Persian\n* Russian\n* Spanish\n* Turkish\n* Ukrainian\n* Uzbek\n:::\n\n\nOne of the first steps of a project is to import outside data into R.\nData is often stored in tabular formats, like csv files or spreadsheets.\n\n- The first half of this cheatsheet shows how to import and save text files into R using **readr**.\n- The second half shows how to import spreadsheet data from Excel files using **readxl** or Google Sheets using **googlesheets4**.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(readr)\nlibrary(readxl)\nlibrary(googlesheets4)\n```\n:::\n\n\nFor importing other types of data try one of the following packages:\n\n- **haven**: SPSS, Stata, and SAS files\n- **DBI**: databases\n- **jsonlite**: json\n- **xml2**: XML\n- **httr**: Web APIs\n- **rvest**: HTML (Web Scraping)\n- **readr::read_lines()**: text data\n\n## Read Tabular Data with readr\n\n\n\n\n\nSee `?read_delim`.\n\n```r\nread_*(\n file, \n col_names = TRUE, col_types = NULL, col_select = NULL, \n show_col_types = TRUE\n id = NULL, locale, \n n_max = Inf, skip = 0, guess_max = min(1000, n_max), \n na = c(\"\", \"NA\")\n)\n```\n\n### Examples\n\n- Read files with any delimiter: `read_delim()`.\n If no delimiter is specified, it will automatically guess.\n\n - If the file you want to import is the following:\n\n ``` \n A|B|C\n 1|2|3\n 4|5|NA\n ```\n\n\n ::: {.cell}\n \n :::\n\n\n - Read it with `read_delim()` and it will look like the following when imported:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_delim(\"file.txt\", delim = \"|\", show_col_types = FALSE)\n ```\n :::\n\n\n - To make `file.txt`, run:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n write_file(\"A|B|C\\n1|2|3\\n4|5|NA\", file = \"file.txt\")\n ```\n :::\n\n\n- Read a comma delimited file with period decimal marks: `read_csv()`.\n\n - If the file you want to import is the following:\n\n ``` \n A,B,C\n 1,2,3\n 4,5,NA\n ```\n\n\n ::: {.cell}\n \n :::\n\n\n - Read it with `read_csv()` and it will look like the following when imported:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_csv(\"file.csv\", show_col_types = FALSE)\n ```\n :::\n\n\n - To make `file.csv`, run:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n write_file(\"A,B,C\\n1,2,3\\n4,5,NA\", file = \"file.csv\")\n ```\n :::\n\n\n- Read semicolon delimited files with comma decimal marks: `read_csv2()`.\n\n - If the file you want to import is the following:\n\n ``` \n A;B;C\n 1,5;2;3\n 4,5;5;NA\n ```\n\n\n ::: {.cell}\n \n :::\n\n\n - Read it with `read_csv2()` and it will look like the following when imported:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_csv2(\"file2.csv\", show_col_types = FALSE)\n ```\n :::\n\n\n - To make `file2.csv`, run:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n write_file(\"A;B;C\\n1,5;2;3\\n4,5;5;NA\", file = \"file2.csv\")\n ```\n :::\n\n\n- Read a tab delimited file: `read_tsv()` or `read_table()`.\n\n Read a fixed width file: `read_fwf(\"file.tsv\", fwf_widths(c(2, 2, NA)))`.\n\n - If the file you want to import is the following:\n\n ``` \n A B C\n 1 2 3\n 4 5 NA\n ```\n\n\n ::: {.cell}\n \n :::\n\n\n - Read it with `read_tsv()` and it will look like the following when imported:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_tsv(\"file.tsv\", show_col_types = FALSE)\n ```\n :::\n\n\n - To make `tsv`, run:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n write_file(\"A\\tB\\tC\\n1\\t2\\t3\\n4\\t5\\tNA\\n\", file = \"file.tsv\")\n ```\n :::\n\n\n### Useful read arguments\n\nSuppose you have the following CSV files that you want to read in, called `file.csv`:\n\n`file.csv`\n\n``` \nA,B,C\n1,2,3\n4,5,NA\n```\n\n`file3.csv`\n\n``` \nA,B,C\n7,8,9\nNA,11,12\n```\n\nTo make these files, run:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nwrite_file(\"A,B,C\\n1,2,3\\n4,5,NA\", file = \"file.csv\")\nwrite_file(\"A,B,C\\n7,8,9\\nNA,11,12\", file = \"file3.csv\")\n```\n:::\n\n\n- No header: `col_names = FALSE`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_csv(\"file.csv\", col_names = FALSE)\n ```\n :::\n\n\n- Provide header: `col_names = c(\"x\", \"y\", \"z\")`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_csv(\"file.csv\", col_names = c(\"x\", \"y\", \"z\"))\n ```\n :::\n\n\n- Skip lines:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_csv(\"file.csv\", skip = 1)\n ```\n :::\n\n\n- Read a subset of lines:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_csv(\"file.csv\", skip = 1)\n ```\n :::\n\n\n- Read values as missing:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_csv(\"file.csv\", na = c(\"1\"))\n ```\n :::\n\n\n- Specify decimal marks:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_delim(\"file2.csv\", locale = locale(decimal_mark = \",\"))\n ```\n :::\n\n\n- Read multiple files into a single table:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_csv(c(\"file.csv\", \"file3.csv\"), id = \"origin_file\")\n ```\n :::\n\n\n### Save data with readr\n\n```r\nwrite_*(\n x, file, \n na = \"NA\", \n append, col_names, quote, escape, eol, num_threads, progress\n)\n```\n\n- Write files with any delimiter: `write_delim(x, file, delim = \" \")`\n- Write a comma delimited file: `write_csv(x, file)`\n- Write a semicolon delimited file: `write_csv2(x, file)`\n- Write a tab delimited file: `write_tsv(x, file)`\n\n### Column specification with readr\n\nColumn specifications define what data type each column of a file will be imported as.\nBy default readr will generate a column spec when a file is read and output a summary.\n\n`spec(df)`: Extract the full column specification for the given imported data frame.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nspec(df)\n# cols(\n# age = col_integer(), # age is an integer\n# edu = col_character(), # edu is a character\n# earn = col_double() # earn is a double (numeric)\n# )\n```\n:::\n\n\n#### Column types\n\nEach column type has a function and corresponding string abbreviation.\n\n- `col_logical() - \"l\"`\n- `col_integer() - \"i\"`\n- `col_double() - \"d\"`\n- `col_number() - \"n\"`\n- `col_character() - \"c\"`\n- `col_factor(levels, ordered = FALSE) - \"f\"`\n- `col_datetime(format = \"\") - \"T\"`\n- `col_date(format = \"\") - \"D\"`\n- `col_time(format = \"\") - \"t\"`\n- `col_skip() - \"-\", \"_\"`\n- `col_guess() - \"?\"`\n\n#### Useful column arguments\n\n- Hide col spec message:\n\n ```r\n read_*(file, show_col_types = FALSE)\n ```\n\n- Select columns to import: Use names, position, or selection helpers.\n\n ```r\n read_*(file, col_select = c(age, earn))\n ```\n\n- Guess column types: To guess a column type, `read_ *()` looks at the first 1000 rows of data.\n Increase with `guess_max`.\n\n ```r\n read_*(file, guess_max = Inf)\n ```\n\n#### Define column specification\n\n- Set a default type:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_csv(\n file, \n col_type = list(.default = col_double())\n )\n ```\n :::\n\n\n- Use column type or string abbreviation:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_csv(\n file, \n col_type = list(x = col_double(), y = \"l\", z = \"_\")\n )\n ```\n :::\n\n\n- Use a single string of abbreviations:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n # col types: skip, guess, integer, logical, character\n read_csv(\n file, \n col_type = \"_?ilc\"\n )\n ```\n :::\n\n\n## Import spreadsheets with readxl\n\n### Read Excel files\n\nRead a .xls or .xlsx file based on the file extension, e.g. `read_excel(\"excel_file.xlsx\")`.\nSee [Useful read arguments] for more read arguments.\nAlso `read_xls()` and `read_xlsx()`.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nread_excel(path, sheet = NULL, range = NULL)\n```\n:::\n\n\n- If the Google sheet you want to import is the following:\n\n | A | B | C | D | E |\n |-----|-----|-----|-----|-----|\n | x1 | x2 | x3 | x4 | x5 |\n | x | | z | 8 | |\n | y | 7 | | 9 | 10 |\n\n : Spreadsheet with 5 columns (A through E) and three rows. First row reads x1 through x5. Second and third row have some missing values.\n\n- It will look like the following when imported:\n\n\n ::: {.cell}\n \n :::\n\n\n### Read sheets\n\n- Specify which sheet to read by position or name: `read_excel(path, sheet = NULL)`\n\n - `read_excel(path, sheet = 1)`\n - `read_excel(path, sheet = \"s1\")`\n\n- Get a vector of sheet names: `excel_sheets(path)`\n\n `excel_sheets(\"excel_file.xlsx\")`\n\n- To read multiple sheets:\n\n 1. Get a vector of sheet names from the file path.\n\n 2. Set the vector names to be the sheet names.\n\n 3. Use `purrr::map_dfr()` to read multiple files into one data frame.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n path <- \"your_file_path.xlsx\"\n path |> excel_sheets() |>\n set_names() |>\n map_dfr(read_excel, path = path)\n ```\n :::\n\n\n### readxl column specification\n\n- Column specifications define what data type each column of a file will be imported as.\n\n- Use the `col_types` argument of `read_excel()` to set the column specification.\n\n- Guess column types: To guess a column type, `read_excel()` looks at the first 1000 rows of data.\n Increase with the `guess_max` argument.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_excel(path, guess_max = Inf)\n ```\n :::\n\n\n- Set all columns to same type, e.g. character:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_excel(path, col_types = \"text\")\n ```\n :::\n\n\n- Set each column individually:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_excel(\n path,\n col_types = c(\"text\", \"guess\", \"guess\",\"numeric\")\n )\n ```\n :::\n\n\n- **Column types:**\n\n | logical | numeric | text | date | list |\n |---------|---------|-------|------------|-------|\n | TRUE | 2 | hello | 1947-01-08 | hello |\n | FALSE | 3.45 | world | 1956-10-21 | 1 |\n\n : Table with 5 columns. Column headers are various data types (logical, numeric, text, date, and list). The data in two rows show examples of data for the given column type.\n\n - `skip`\n\n - `guess`\n\n - `logical`\n\n - `date`\n\n - `numeric`\n\n - `text`\n\n - Use `list`for columns that include multiple data types.\n See **tidyr** and **purrr** for list-column data.\n\n### Other useful Excel packages\n\n- For functions to write data to Excel files: **openxlsx** and **writexl**\n- For working with non-tabular Excel data: **tidyxl**\n\n## Import spreadsheets with googlesheets4\n\n### Read sheets\n\nRead a sheet from a URL, a Sheet ID, or a dribble samefrom the googledrive package.\nSee [Useful read arguments] for more read arguments.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nread_sheet(ss, sheet = NULL, range = NULL)\n```\n:::\n\n\nSame as `range_read()`.\n\n- If the Google sheet you want to import is the following:\n\n | A | B | C | D | E |\n |-----|-----|-----|-----|-----|\n | x1 | x2 | x3 | x4 | x5 |\n | x | | z | 8 | |\n | y | 7 | | 9 | 10 |\n\n : Spreadsheet with 5 columns (A through E) and three rows. First row reads x1 through x5. Second and third row have some missing values.\n\n- It will look like the following when imported:\n\n\n ::: {.cell}\n \n :::\n\n\n### Sheet metadata\n\n- **URLs** are in the form:\n\n ``` \n https://docs.google.com/spreadsheets/d/\n             SPREADSHEET_ID/edit#gid=SHEET_ID\n ```\n\n- Get spreadsheet meta data: `gs4_get(ss)`\n\n- Get data on all spreadsheet files: `gs4_find(...)`\n\n- Get a tibble of properties for each worksheet: `sheet_properties(ss)`.\n Also `sheet_names()`.\n\n### Write sheets\n\n- `write_sheet(data, ss = NULL, sheet = NULL)`**:** Write a data frame into a new or existing Sheet. \n- `gs4_create(name, ..., sheets = NULL)`: Create a new Sheet with a vector of names, a data frame, or a (named) list of data frames.\n- `sheet_append(ss, data, sheet = 1)`: Add rows to the end of a worksheet.\n\n### googlesheets4 column specification\n\nColumn specifications define what data type each column of a file will be imported as.\n\nUse the `col_types` argument of `read_sheet()`**/**`range_read()` to set the column specification.\n\n- Guess column types: To guess a column type `read_sheet()`/`range_read()` looks at the first 1000 rows of data.\n Increase with `guess_max`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_sheet(path, guess_max = Inf)\n ```\n :::\n\n\n- Set all columns to same type, e.g. character:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_sheet(path, col_types = \"c\")\n ```\n :::\n\n\n- Set each column individually:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n # col types: skip, guess, integer, logical, character\n read_sheets(ss, col_types = \"_?ilc\")\n ```\n :::\n\n\n- Column types:\n\n - skipped my lunch 🥙 🍱 and: \"\\_\" or \"-\"\n\n - guess: \"?\"\n\n - logical: \"l\"\n\n - integer: \"i\"\n\n - double: \"d\"\n\n - numeric: \"n\"\n\n - date: \"D\"\n\n - datetime: \"T\"\n\n - character: \"c\"\n\n - list-column: \"L\"\n\n - cell: \"C\" (returns list of raw cell data)\n\n - Use list for columns that include multiple data types.\n See **tidyr** and **purrr** for list-column data.\n\n### File level operations\n\n- **googlesheets4** also offers ways to modify other aspects of Sheets (e.g. freeze rows, set column width, manage (work)sheets). Go to [googlesheets4.tidyverse.org](https://googlesheets4.tidyverse.org/) to read more.\n- For whole-file operations (e.g. renaming, sharing, placing within a folder), see the tidyverse package **googledrive** at [googledrive.tidyverse.org](https://googledrive.tidyverse.org).\n\n## Cell specification for readxl and googlesheets4\n\nUse the **range** argument of **readxl::read_excel()** or **googlesheets4::read_sheet()** to read a subset of cells from a sheet.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nread_excel(path, range = \"Sheet1!B1:D2\")\nread_sheet(ss, range = \"B1:D2\")\n```\n:::\n\n\nAlso use the range argument with cell specification functions `cell_limits()`, `cell_rows()`, `cell_cols()`, and `anchored()`**.**\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at\n\n- readr: [readr.tidyverse.org](https://readr.tidyverse.org)\n- readxl: [readxl.tidyverse.org](https://readxl.tidyverse.org/)\n- googlesheets4: [googlesheets4.tidyverse.org](https://googlesheets4.tidyverse.org/)\n\nUpdated: 2023-05.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"readr\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '2.1.4'\n```\n:::\n\n```{.r .cell-code}\npackageVersion(\"readxl\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.4.2'\n```\n:::\n\n```{.r .cell-code}\npackageVersion(\"googlesheets4\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.1.0'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n\n\n\n", - "supporting": [], + "markdown": "---\ntitle: \"Data import with the tidyverse :: Cheatsheet\"\ndescription: \" \"\nexecute:\n eval: true\n output: false\n warning: true\n---\n\n::: {.cell .column-margin}\n\"Hex\n

\n

Download PDF

\n\"\"/\n
\n

Translations (PDF)

\n* Bengali\n* Persian\n* Russian\n* Spanish\n* Turkish\n* Ukrainian\n* Uzbek\n:::\n\n\nOne of the first steps of a project is to import outside data into R.\nData is often stored in tabular formats, like csv files or spreadsheets.\n\n- The first half of this cheatsheet shows how to import and save text files into R using **readr**.\n- The second half shows how to import spreadsheet data from Excel files using **readxl** or Google Sheets using **googlesheets4**.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(readr)\nlibrary(readxl)\nlibrary(googlesheets4)\n```\n:::\n\n\nFor importing other types of data try one of the following packages:\n\n- **haven**: SPSS, Stata, and SAS files\n- **DBI**: databases\n- **jsonlite**: json\n- **xml2**: XML\n- **httr**: Web APIs\n- **rvest**: HTML (Web Scraping)\n- **readr::read_lines()**: text data\n\n## Read Tabular Data with readr\n\n\n\n\n\nSee `?read_delim`.\n\n``` r\nread_*(\n file, \n col_names = TRUE, col_types = NULL, col_select = NULL, \n show_col_types = TRUE\n id = NULL, locale, \n n_max = Inf, skip = 0, guess_max = min(1000, n_max), \n na = c(\"\", \"NA\")\n)\n```\n\n### Examples\n\n- Read files with any delimiter: `read_delim()`.\n If no delimiter is specified, it will automatically guess.\n\n - If the file you want to import is the following:\n\n ``` \n A|B|C\n 1|2|3\n 4|5|NA\n ```\n\n\n ::: {.cell}\n \n :::\n\n\n - Read it with `read_delim()` and it will look like the following when imported:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_delim(\"file.txt\", delim = \"|\", show_col_types = FALSE)\n ```\n :::\n\n\n - To make `file.txt`, run:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n write_file(\"A|B|C\\n1|2|3\\n4|5|NA\", file = \"file.txt\")\n ```\n :::\n\n\n- Read a comma delimited file with period decimal marks: `read_csv()`.\n\n - If the file you want to import is the following:\n\n ``` \n A,B,C\n 1,2,3\n 4,5,NA\n ```\n\n\n ::: {.cell}\n \n :::\n\n\n - Read it with `read_csv()` and it will look like the following when imported:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_csv(\"file.csv\", show_col_types = FALSE)\n ```\n :::\n\n\n - To make `file.csv`, run:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n write_file(\"A,B,C\\n1,2,3\\n4,5,NA\", file = \"file.csv\")\n ```\n :::\n\n\n- Read semicolon delimited files with comma decimal marks: `read_csv2()`.\n\n - If the file you want to import is the following:\n\n ``` \n A;B;C\n 1,5;2;3\n 4,5;5;NA\n ```\n\n\n ::: {.cell}\n \n :::\n\n\n - Read it with `read_csv2()` and it will look like the following when imported:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_csv2(\"file2.csv\", show_col_types = FALSE)\n ```\n :::\n\n\n - To make `file2.csv`, run:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n write_file(\"A;B;C\\n1,5;2;3\\n4,5;5;NA\", file = \"file2.csv\")\n ```\n :::\n\n\n- Read a tab delimited file: `read_tsv()` or `read_table()`.\n\n Read a fixed width file: `read_fwf(\"file.tsv\", fwf_widths(c(2, 2, NA)))`.\n\n - If the file you want to import is the following:\n\n ``` \n A B C\n 1 2 3\n 4 5 NA\n ```\n\n\n ::: {.cell}\n \n :::\n\n\n - Read it with `read_tsv()` and it will look like the following when imported:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_tsv(\"file.tsv\", show_col_types = FALSE)\n ```\n :::\n\n\n - To make `tsv`, run:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n write_file(\"A\\tB\\tC\\n1\\t2\\t3\\n4\\t5\\tNA\\n\", file = \"file.tsv\")\n ```\n :::\n\n\n### Useful read arguments\n\nSuppose you have the following CSV files that you want to read in, called `file.csv`:\n\n`file.csv`\n\n``` \nA,B,C\n1,2,3\n4,5,NA\n```\n\n`file3.csv`\n\n``` \nA,B,C\n7,8,9\nNA,11,12\n```\n\nTo make these files, run:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nwrite_file(\"A,B,C\\n1,2,3\\n4,5,NA\", file = \"file.csv\")\nwrite_file(\"A,B,C\\n7,8,9\\nNA,11,12\", file = \"file3.csv\")\n```\n:::\n\n\n- No header: `col_names = FALSE`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_csv(\"file.csv\", col_names = FALSE)\n ```\n :::\n\n\n- Provide header: `col_names = c(\"x\", \"y\", \"z\")`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_csv(\"file.csv\", col_names = c(\"x\", \"y\", \"z\"))\n ```\n :::\n\n\n- Skip lines:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_csv(\"file.csv\", skip = 1)\n ```\n :::\n\n\n- Read a subset of lines:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_csv(\"file.csv\", skip = 1)\n ```\n :::\n\n\n- Read values as missing:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_csv(\"file.csv\", na = c(\"1\"))\n ```\n :::\n\n\n- Specify decimal marks:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_delim(\"file2.csv\", locale = locale(decimal_mark = \",\"))\n ```\n :::\n\n\n- Read multiple files into a single table:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_csv(c(\"file.csv\", \"file3.csv\"), id = \"origin_file\")\n ```\n :::\n\n\n### Save data with readr\n\n``` r\nwrite_*(\n x, file, \n na = \"NA\", \n append, col_names, quote, escape, eol, num_threads, progress\n)\n```\n\n- Write files with any delimiter: `write_delim(x, file, delim = \" \")`\n- Write a comma delimited file: `write_csv(x, file)`\n- Write a semicolon delimited file: `write_csv2(x, file)`\n- Write a tab delimited file: `write_tsv(x, file)`\n\n### Column specification with readr\n\nColumn specifications define what data type each column of a file will be imported as.\nBy default readr will generate a column spec when a file is read and output a summary.\n\n`spec(df)`: Extract the full column specification for the given imported data frame.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nspec(df)\n# cols(\n# age = col_integer(), # age is an integer\n# edu = col_character(), # edu is a character\n# earn = col_double() # earn is a double (numeric)\n# )\n```\n:::\n\n\n#### Column types\n\nEach column type has a function and corresponding string abbreviation.\n\n- `col_logical() - \"l\"`\n- `col_integer() - \"i\"`\n- `col_double() - \"d\"`\n- `col_number() - \"n\"`\n- `col_character() - \"c\"`\n- `col_factor(levels, ordered = FALSE) - \"f\"`\n- `col_datetime(format = \"\") - \"T\"`\n- `col_date(format = \"\") - \"D\"`\n- `col_time(format = \"\") - \"t\"`\n- `col_skip() - \"-\", \"_\"`\n- `col_guess() - \"?\"`\n\n#### Useful column arguments\n\n- Hide col spec message:\n\n ``` r\n read_*(file, show_col_types = FALSE)\n ```\n\n- Select columns to import: Use names, position, or selection helpers.\n\n ``` r\n read_*(file, col_select = c(age, earn))\n ```\n\n- Guess column types: To guess a column type, `read_ *()` looks at the first 1000 rows of data.\n Increase with `guess_max`.\n\n ``` r\n read_*(file, guess_max = Inf)\n ```\n\n#### Define column specification\n\n- Set a default type:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_csv(\n file, \n col_type = list(.default = col_double())\n )\n ```\n :::\n\n\n- Use column type or string abbreviation:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_csv(\n file, \n col_type = list(x = col_double(), y = \"l\", z = \"_\")\n )\n ```\n :::\n\n\n- Use a single string of abbreviations:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n # col types: skip, guess, integer, logical, character\n read_csv(\n file, \n col_type = \"_?ilc\"\n )\n ```\n :::\n\n\n## Import spreadsheets with readxl\n\n### Read Excel files\n\nRead a .xls or .xlsx file based on the file extension, e.g. `read_excel(\"excel_file.xlsx\")`.\nSee [Useful read arguments] for more read arguments.\nAlso `read_xls()` and `read_xlsx()`.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nread_excel(path, sheet = NULL, range = NULL)\n```\n:::\n\n\n- If the Google sheet you want to import is the following:\n\n | A | B | C | D | E |\n |-----|-----|-----|-----|-----|\n | x1 | x2 | x3 | x4 | x5 |\n | x | | z | 8 | |\n | y | 7 | | 9 | 10 |\n\n : Spreadsheet with 5 columns (A through E) and three rows. First row reads x1 through x5. Second and third row have some missing values.\n\n- It will look like the following when imported:\n\n\n ::: {.cell}\n \n :::\n\n\n### Read sheets\n\n- Specify which sheet to read by position or name: `read_excel(path, sheet = NULL)`\n\n - `read_excel(path, sheet = 1)`\n - `read_excel(path, sheet = \"s1\")`\n\n- Get a vector of sheet names: `excel_sheets(path)`\n\n `excel_sheets(\"excel_file.xlsx\")`\n\n- To read multiple sheets:\n\n 1. Get a vector of sheet names from the file path.\n\n 2. Set the vector names to be the sheet names.\n\n 3. Use `purrr::map_dfr()` to read multiple files into one data frame.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n path <- \"your_file_path.xlsx\"\n path |> excel_sheets() |>\n set_names() |>\n map_dfr(read_excel, path = path)\n ```\n :::\n\n\n### readxl column specification\n\n- Column specifications define what data type each column of a file will be imported as.\n\n- Use the `col_types` argument of `read_excel()` to set the column specification.\n\n- Guess column types: To guess a column type, `read_excel()` looks at the first 1000 rows of data.\n Increase with the `guess_max` argument.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_excel(path, guess_max = Inf)\n ```\n :::\n\n\n- Set all columns to same type, e.g. character:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_excel(path, col_types = \"text\")\n ```\n :::\n\n\n- Set each column individually:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_excel(\n path,\n col_types = c(\"text\", \"guess\", \"guess\",\"numeric\")\n )\n ```\n :::\n\n\n- **Column types:**\n\n | logical | numeric | text | date | list |\n |---------|---------|-------|------------|-------|\n | TRUE | 2 | hello | 1947-01-08 | hello |\n | FALSE | 3.45 | world | 1956-10-21 | 1 |\n\n : Table with 5 columns. Column headers are various data types (logical, numeric, text, date, and list). The data in two rows show examples of data for the given column type.\n\n - `skip`\n\n - `guess`\n\n - `logical`\n\n - `date`\n\n - `numeric`\n\n - `text`\n\n - Use `list`for columns that include multiple data types.\n See **tidyr** and **purrr** for list-column data.\n\n### Other useful Excel packages\n\n- For functions to write data to Excel files: **openxlsx** and **writexl**\n- For working with non-tabular Excel data: **tidyxl**\n\n## Import spreadsheets with googlesheets4\n\n### Read sheets\n\nRead a sheet from a URL, a Sheet ID, or a dribble samefrom the googledrive package.\nSee [Useful read arguments] for more read arguments.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nread_sheet(ss, sheet = NULL, range = NULL)\n```\n:::\n\n\nSame as `range_read()`.\n\n- If the Google sheet you want to import is the following:\n\n | A | B | C | D | E |\n |-----|-----|-----|-----|-----|\n | x1 | x2 | x3 | x4 | x5 |\n | x | | z | 8 | |\n | y | 7 | | 9 | 10 |\n\n : Spreadsheet with 5 columns (A through E) and three rows. First row reads x1 through x5. Second and third row have some missing values.\n\n- It will look like the following when imported:\n\n\n ::: {.cell}\n \n :::\n\n\n### Sheet metadata\n\n- **URLs** are in the form:\n\n ``` \n https://docs.google.com/spreadsheets/d/\n             SPREADSHEET_ID/edit#gid=SHEET_ID\n ```\n\n- Get spreadsheet meta data: `gs4_get(ss)`\n\n- Get data on all spreadsheet files: `gs4_find(...)`\n\n- Get a tibble of properties for each worksheet: `sheet_properties(ss)`.\n Also `sheet_names()`.\n\n### Write sheets\n\n- `write_sheet(data, ss = NULL, sheet = NULL)`**:** Write a data frame into a new or existing Sheet. \n- `gs4_create(name, ..., sheets = NULL)`: Create a new Sheet with a vector of names, a data frame, or a (named) list of data frames.\n- `sheet_append(ss, data, sheet = 1)`: Add rows to the end of a worksheet.\n\n### googlesheets4 column specification\n\nColumn specifications define what data type each column of a file will be imported as.\n\nUse the `col_types` argument of `read_sheet()`**/**`range_read()` to set the column specification.\n\n- Guess column types: To guess a column type `read_sheet()`/`range_read()` looks at the first 1000 rows of data.\n Increase with `guess_max`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_sheet(path, guess_max = Inf)\n ```\n :::\n\n\n- Set all columns to same type, e.g. character:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n read_sheet(path, col_types = \"c\")\n ```\n :::\n\n\n- Set each column individually:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n # col types: skip, guess, integer, logical, character\n read_sheets(ss, col_types = \"_?ilc\")\n ```\n :::\n\n\n- Column types:\n\n - skipped my lunch 🥙 🍱 and: \"\\_\" or \"-\"\n\n - guess: \"?\"\n\n - logical: \"l\"\n\n - integer: \"i\"\n\n - double: \"d\"\n\n - numeric: \"n\"\n\n - date: \"D\"\n\n - datetime: \"T\"\n\n - character: \"c\"\n\n - list-column: \"L\"\n\n - cell: \"C\" (returns list of raw cell data)\n\n - Use list for columns that include multiple data types.\n See **tidyr** and **purrr** for list-column data.\n\n### File level operations\n\n- **googlesheets4** also offers ways to modify other aspects of Sheets (e.g. freeze rows, set column width, manage (work)sheets). Go to [googlesheets4.tidyverse.org](https://googlesheets4.tidyverse.org/) to read more.\n- For whole-file operations (e.g. renaming, sharing, placing within a folder), see the tidyverse package **googledrive** at [googledrive.tidyverse.org](https://googledrive.tidyverse.org).\n\n## Cell specification for readxl and googlesheets4\n\nUse the **range** argument of **readxl::read_excel()** or **googlesheets4::read_sheet()** to read a subset of cells from a sheet.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nread_excel(path, range = \"Sheet1!B1:D2\")\nread_sheet(ss, range = \"B1:D2\")\n```\n:::\n\n\nAlso use the range argument with cell specification functions `cell_limits()`, `cell_rows()`, `cell_cols()`, and `anchored()`**.**\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at\n\n- readr: [readr.tidyverse.org](https://readr.tidyverse.org)\n- readxl: [readxl.tidyverse.org](https://readxl.tidyverse.org/)\n- googlesheets4: [googlesheets4.tidyverse.org](https://googlesheets4.tidyverse.org/)\n\nUpdated: 2023-06.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"readr\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '2.1.4'\n```\n:::\n\n```{.r .cell-code}\npackageVersion(\"readxl\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.4.2'\n```\n:::\n\n```{.r .cell-code}\npackageVersion(\"googlesheets4\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.1.0'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n\n\n\n", + "supporting": [ + "data-import_files" + ], "filters": [ "rmarkdown/pagebreak.lua" ], diff --git a/_freeze/html/data-transformation/execute-results/html.json b/_freeze/html/data-transformation/execute-results/html.json index 949920a7..6e3caa57 100644 --- a/_freeze/html/data-transformation/execute-results/html.json +++ b/_freeze/html/data-transformation/execute-results/html.json @@ -1,7 +1,7 @@ { - "hash": "68bd60b1120f2c4f3bb7d967d882f815", + "hash": "093850b320e37db2fe88cf7417fff21f", "result": { - "markdown": "---\ntitle: \"Data transformation with dplyr :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: false\n---\n\n::: {.cell .column-margin}\n\"\"\n

\n

Download PDF

\n\n
\n

Translations (PDF)

\n* Chinese\n* German\n* Russian\n* Spanish\n* Turkish\n* Ukrainian\n* Uzbek\n:::\n\n\n\n\n**dplyr** functions work with pipes and expect **tidy data**.\nIn tidy data:\n\n- Each **variable** is in its own **column**\n- Each **observation**, or **case**, is in its own **row**\n- **pipes** `x |> f(y)` becomes `f(x,y)`\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(dplyr)\n```\n:::\n\n\n\n\n## Summarize Cases\n\nApply **summary** functions to columns to create a new table of summary statistics.\nSummary functions take vectors as input and return one value back (see Summary Functions).\n\n- `summarize(.data, ...)`: Compute table of summaries.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> summarize(avg = mean(mpg))\n ```\n :::\n\n\n- `count(.data, ..., wt = NULL, sort = FLASE, name = NULL)`: Count number of rows in each group defined by the variables in `...`.\n Also `tally()`, `add_count()`, and `add_tally()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> summarize(cyl)\n ```\n :::\n\n\n## Group Cases\n\n- Use `group_by(.data, ..., .add = FALSE, .drop = TRUE)` to created a \"grouped\" copy of a table grouped by columns in `...`.\n dplyr functions will manipulate each \"group\" separately and combine the results.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |>\n group_by(cyl) |>\n summarize(avg = mean(mpg))\n ```\n :::\n\n\n- Use `rowwise(.data, ...)` to group data into individual rows.\n dplyr functions will compute results for each row.\n Also apply functions to list-columns.\n See tidyr cheatsheet for list-column workflow.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n starwars |>\n rowwise() |>\n mutate(film_count = length(films))\n ```\n :::\n\n\n- `ungroup(x, ...)`: Returns ungrouped copy of table.\n\n\n \n\n\n## Manipulate Cases\n\n### Extract Cases\n\nRow functions return a subset of rows as a new table.\n\n- `filter(.data, ..., .preserve = FALSE)`: Extract rows that meet logical criteria.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> filter(mpg > 20)\n ```\n :::\n\n\n- `distinct(.data, ..., .keep_all = FALSE)`: Remove rows with duplicate values.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> distinct(gear)\n ```\n :::\n\n\n- `slice(.data, ...,, .preserve = FALSE)`: Select rows by position.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> slice(10:15)\n ```\n :::\n\n\n- `slice_sample(.data, ..., n, prop, weight_by = NULL, replace = FALSE)`: Randomly select rows.\n Use `n` to select a number of rows and `prop` to select a fraction of rows.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> slice_sample(n = 5, replace = TRUE)\n ```\n :::\n\n\n- `slice_min(.data, order_by, ..., n, prop, with_ties = TRUE)` and `slice_max()`: Select rows with the lowest and highest values.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> slice_min(mpg, prop = 0.25)\n ```\n :::\n\n\n- `slice_head(.data, ..., n, prop)` and `slice_tail()`: Select the first or last rows.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> slice_head(n = 5)\n ```\n :::\n\n\n#### Logical and boolean operations to use with `filter()`\n\n- `==`\n- `<`\n- `<=`\n- `is.na()`\n- `%in%`\n- `|`\n- `xor()`\n- `!=`\n- `>`\n- `>=`\n- `!is.na()`\n- `!`\n- `&`\n- See `?base::Logic` and `?Comparison` for help.\n\n### Arrange cases\n\n- `arrange(.data, ..., .by_group = FALSE)`: Order rows by values of a column or columns (low to high), use with `desc()` to order from high to low.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> arrange(mpg)\n mtcars |> arrange(desc(mpg))\n ```\n :::\n\n\n### Add Cases\n\n- `add_row(.data, ..., .before = NULL, .after = NULL)`: Add one or more rows to a table.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n cars |> add_row(speed = 1, dist = 1)\n ```\n :::\n\n\n## Manipulate Variables\n\n### Extract Variables\n\nColumn functions return a set of columns as a new vector or table.\n\n- `pull(.data, var = -1, name = NULL, ...)`: Extract column values as a vector, by name or index.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> pull(wt)\n ```\n :::\n\n\n- `select(.data, ...)`: Extract columns as a table.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> select(mpg, wt)\n ```\n :::\n\n\n- `relocate(.data, ..., .before = NULL, .after = NULL)`: Move columns to new position.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> relocate(mpg, cyl, after = last_col())\n ```\n :::\n\n\n#### Use these helpers with `select()` and `across()`\n\n\n::: {.cell}\n\n```{.r .cell-code}\nmtcars |> select(mpg:cyl)\n```\n:::\n\n\n- `contains(match)`\n- `num_range(prefix, range)`\n- `:`, e.g., `mpg:cyl`\n- `ends_with(match)`\n- `all_of(x)` or `any_of(x, ..., vars)`\n- `!`, e.g., `!gear`\n- `starts_with(match)`\n- `matches(match)`\n- `everything()`\n\n### Manipulate Multiple Variables at Once\n\n\n::: {.cell}\n\n```{.r .cell-code}\ndf <- tibble(x_1 = c(1, 2), x_2 = c(3, 4), y = c(4, 5))\n```\n:::\n\n\n- `across(.cols, .fun, ..., .name = NULL)`: summarize or mutate multiple columns in the same way.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n df |> summarize(across(everything(), mean))\n ```\n :::\n\n\n- `c_across(.cols)`: Compute across columns in row-wise data.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n df |> \n rowwise() |>\n mutate(x_total = sum(c_across(1:2)))\n ```\n :::\n\n\n### Make New Variables\n\nApply **vectorized functions** to columns.\nVectorized functions take vectors as input and return vectors of the same length as output (see Vectorized Functions).\n\n- `mutate(.data, ..., .keep = \"all\", .before = NULL, .after = NULL)`: Compute new column(s).\n Also `add_column()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> mutate(gpm = 1 / mpg)\n mtcars |> mutate(mtcars, gpm = 1 / mpg, .keep = \"none\")\n ```\n :::\n\n\n- `rename(.data, ...)`: Rename columns.\n Use `rename_with()` to rename with a function.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> rename(miles_per_gallon = mpg)\n ```\n :::\n\n\n\n\n## Vectorized Functions\n\n### To Use with `mutate()`\n\n`mutate()` applies vectorized functions to columns to create new columns.\nVectorized functions take vectors as input and return vectors of the same length as output.\n\n### Offset\n\n- `dplyr::lag()`: offset elements by 1\n- `dplyr::lead()`: offset elements by -1\n\n### Cumulative Aggregate\n\n- `dplyr::cumall()`: cumulative `all()`\n- `dply::cumany()`: cumulative `any()`\n- `cummax()`: cumulative `max()`\n- `dplyr::cummean()`: cumulative `mean()`\n- `cummin()`: cumulative `min()`\n- `cumprod()`: cumulative `prod()`\n- `cumsum()`: cumulative `sum()`\n\n### Ranking\n\n- `dplyr::cume_dist()`: proportion of all values \\<=\n- `dplyr::dense_rank()`: rank with ties = min, no gaps\n- `dplyr::min_rank()`: rank with ties = min\n- `dplyr::ntile()`: bins into n bins\n- `dplyr::percent_rank()`: `min_rank()` scaled to \\[0,1\\]\n- `dplyr::row_number()`: rank with ties = \"first\"\n\n### Math\n\n- `+`, `-`, `/`, `^`, `%/%`, `%%`: arithmetic ops\n- `log()`, `log2()`, `log10()`: logs\n- `<`, `<=`, `>`, `>=`, `!=`, `==`: logical comparisons\n- `dplyr::between()`: x \\>= left & x \\<= right\n- `dplyr::near()`: safe `==` for floating point numbers\n\n### Miscellaneous\n\n- `dplyr::case_when()`: multi-case `if_else()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n starwars |>\n mutate(type = case_when(\n height > 200 | mass > 200 ~ \"large\",\n species == \"Droid\" ~ \"robot\",\n TRUE ~ \"other\"\n ))\n ```\n :::\n\n\n- `dplyr::coalesce()`: first non-NA values by element across a set of vectors\n\n- `dplyr::if_else()`: element-wise if() + else()\n\n- `dplyr::na_if()`: replace specific values with NA\n\n- `pmax()`: element-wise max()\n\n- `pmin()`: element-wise min()\n\n## Summary Functions\n\n### To Use with `summarize()`\n\n`summarize()` applies summary functions to columns to create a new table.\nSummary functions take vectors as input and return single values as output.\n\n### Count\n\n- `dplyr::n()`: number of values/rows\n- `dplyr::n_distinct()`: \\# of uniques\n- `sum(!is.na())`: \\# of non-NAs\n\n### Position\n\n- `mean()`: mean, also `mean(!is.na())`\n- `median()`: median\n\n### Logical\n\n- `mean()`: proportion of TRUEs\n- `sum()`: \\# of TRUEs\n\n### Order\n\n- `dplyr::first()`: first value\n- `dplyr::last()`: last value\n- `dplyr::nth()`: value in the nth location of vector\n\n### Rank\n\n- `quantile()`: nth quantile\n- `min()`: minimum value\n- `max()`: maximum value\n\n### Spread\n\n- `IQR()`: Inter-Quartile Range\n- `mad()`: median absolute deviation\n- `sd()`: standard deviation\n- `var()`: variance\n\n## Row Names\n\nTidy data does not use rownames, which store a variable outside of the columns.\nTo work with the rownames, first move them into a column.\n\n- `tibble::rownames_to_column()`: Move row names into col.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n a <- rownames_to_column(mtcars, var = \"C\")\n ```\n :::\n\n\n- `tibble::columns_to_rownames()`: Move col into row names.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n column_to_rownames(a, var = \"C\")\n ```\n :::\n\n\n- Also `tibble::has_rownames()` and `tibble::remove_rownames()`.\n\n## Combine Tables\n\n\n::: {.cell}\n\n```{.r .cell-code}\nx <- tribble(\n ~A, ~B, ~C,\n \"a\", \"t\", 1,\n \"b\", \"u\", 2,\n \"c\", \"v\", 3\n)\n\ny <- tribble(\n ~A, ~B, ~D,\n \"a\", \"t\", 3,\n \"b\", \"u\", 2,\n \"d\", \"w\", 1\n)\n```\n:::\n\n\n### Combine Variables\n\n- `bind_cols(..., .name_repair)`: Returns tables placed side by side as a single table. Column lengths must be equal. Columns will NOT be matched by id (to do that look at Relational Data below), so be sure to check that both tables are ordered the way you want before binding.\n\n### Combine Cases\n\n- `bind_rows(..., .id = NULL)`: Returns tables one on top of the other as a single table. Set `.id` to a column name to add a column of the original table names.\n\n### Relational Data\n\nUse a **\"Mutating Join\"** to join one table to columns from another, matching values with the rows that the correspond to.\nEach join retains a different combination of values from the tables.\n\n- `left_join(x, y, by = NULL, copy = FALSE, suffix = c(\".x\", \".y\"), ..., keep = FALSE, na_matches = \"na\")`: Join matching values from `y` to `x`.\n- `right_join(x, y, by = NULL, copy = FALSE, suffix = c(\".x\", \".y\"), ..., keep = FALSE, na_matches = \"na\")`: Join matching values from `x` to `y`.\n- `inner_join(x, y, by = NULL, copy = FALSE, suffix = c(\".x\", \".y\"), ..., keep = FALSE, na_matches = \"na\")`: Join data. retain only rows with matches.\n- `full_join(x, y, by = NULL, copy = FALSE, suffix = c(\".x\", \".y\"), ..., keep = FALSE, na_matches = \"na\")`: Join data. Retain all values, all rows.\n\nUse a **\"Filtering Join\"** to filter one table against the rows of another.\n\n- `semi_join(x, y, by = NULL, copy = FALSE, ..., na_matches = \"na\")`: Return rows of `x` that have a match in `y`. Use to see what will be included in a join.\n- `anti_join(x, y, by = NULL, copy = FALSE, ..., na_matches = \"na\")`: Return rows of `x` that do not have a match in `y`. Use to see what will not be included in a join.\n\nUse a **\"Nest Join\"** to inner join one table to another into a nested data frame.\n\n- `nest_join(x, y, by = NULL, copy = FALSE, keep = FALSE, name = NULL, ...)`: Join data, nesting matches from `y` in a single new data frame column.\n\n### Column Matching for Joins\n\n- Use `by = c(\"col1\", \"col2\", ...)` to specify one or more common columns to match on.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n left_join(x, y, by = \"A\")\n ```\n :::\n\n\n- Use a named vector, `by = c(\"col1\" = \"col2\")`, to match on columns that have different names in each table.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n left_join(x, y, by = c(\"C\" = \"D\"))\n ```\n :::\n\n\n- Use `suffix` to specify the suffix to give to unmatched columns that have the same name in both tables.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n left_join(x, y, by = c(\"C\" = \"D\"), suffix = c(\"1\", \"2\"))\n ```\n :::\n\n\n### Set Operations\n\n- `intersect(x, y, ...)`: Rows that appear in both `x` and `y`.\n- `setdiff(x, y, ...)`: Rows that appear in `x` but not `y`.\n- `union(x, y, ...)`: Rows that appear in x or y, duplicates removed. `union_all()` retains duplicates.\n- Use `setequal()` to test whether two data sets contain the exact same rows (in any order).\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [dplyr.tidyverse.org](https://dplyr.tidyverse.org).\n\nUpdated: 2023-05.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"dplyr\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.1.2'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", + "markdown": "---\ntitle: \"Data transformation with dplyr :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: false\n---\n\n::: {.cell .column-margin}\n\"Hex\n

\n

Download PDF

\n\"\"/\n
\n

Translations (PDF)

\n* Chinese\n* German\n* Russian\n* Spanish\n* Turkish\n* Ukrainian\n* Uzbek\n:::\n\n\n\n\n**dplyr** functions work with pipes and expect **tidy data**.\nIn tidy data:\n\n- Each **variable** is in its own **column**\n- Each **observation**, or **case**, is in its own **row**\n- **pipes** `x |> f(y)` becomes `f(x,y)`\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(dplyr)\n```\n:::\n\n\n\n\n## Summarize Cases\n\nApply **summary** functions to columns to create a new table of summary statistics.\nSummary functions take vectors as input and return one value back (see Summary Functions).\n\n- `summarize(.data, ...)`: Compute table of summaries.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> summarize(avg = mean(mpg))\n ```\n :::\n\n\n- `count(.data, ..., wt = NULL, sort = FLASE, name = NULL)`: Count number of rows in each group defined by the variables in `...`.\n Also `tally()`, `add_count()`, and `add_tally()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> summarize(cyl)\n ```\n :::\n\n\n## Group Cases\n\n- Use `group_by(.data, ..., .add = FALSE, .drop = TRUE)` to created a \"grouped\" copy of a table grouped by columns in `...`.\n dplyr functions will manipulate each \"group\" separately and combine the results.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |>\n group_by(cyl) |>\n summarize(avg = mean(mpg))\n ```\n :::\n\n\n- Use `rowwise(.data, ...)` to group data into individual rows.\n dplyr functions will compute results for each row.\n Also apply functions to list-columns.\n See tidyr cheatsheet for list-column workflow.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n starwars |>\n rowwise() |>\n mutate(film_count = length(films))\n ```\n :::\n\n\n- `ungroup(x, ...)`: Returns ungrouped copy of table.\n\n\n \n\n\n## Manipulate Cases\n\n### Extract Cases\n\nRow functions return a subset of rows as a new table.\n\n- `filter(.data, ..., .preserve = FALSE)`: Extract rows that meet logical criteria.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> filter(mpg > 20)\n ```\n :::\n\n\n- `distinct(.data, ..., .keep_all = FALSE)`: Remove rows with duplicate values.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> distinct(gear)\n ```\n :::\n\n\n- `slice(.data, ...,, .preserve = FALSE)`: Select rows by position.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> slice(10:15)\n ```\n :::\n\n\n- `slice_sample(.data, ..., n, prop, weight_by = NULL, replace = FALSE)`: Randomly select rows.\n Use `n` to select a number of rows and `prop` to select a fraction of rows.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> slice_sample(n = 5, replace = TRUE)\n ```\n :::\n\n\n- `slice_min(.data, order_by, ..., n, prop, with_ties = TRUE)` and `slice_max()`: Select rows with the lowest and highest values.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> slice_min(mpg, prop = 0.25)\n ```\n :::\n\n\n- `slice_head(.data, ..., n, prop)` and `slice_tail()`: Select the first or last rows.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> slice_head(n = 5)\n ```\n :::\n\n\n#### Logical and boolean operations to use with `filter()`\n\n- `==`\n- `<`\n- `<=`\n- `is.na()`\n- `%in%`\n- `|`\n- `xor()`\n- `!=`\n- `>`\n- `>=`\n- `!is.na()`\n- `!`\n- `&`\n- See `?base::Logic` and `?Comparison` for help.\n\n### Arrange cases\n\n- `arrange(.data, ..., .by_group = FALSE)`: Order rows by values of a column or columns (low to high), use with `desc()` to order from high to low.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> arrange(mpg)\n mtcars |> arrange(desc(mpg))\n ```\n :::\n\n\n### Add Cases\n\n- `add_row(.data, ..., .before = NULL, .after = NULL)`: Add one or more rows to a table.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n cars |> add_row(speed = 1, dist = 1)\n ```\n :::\n\n\n## Manipulate Variables\n\n### Extract Variables\n\nColumn functions return a set of columns as a new vector or table.\n\n- `pull(.data, var = -1, name = NULL, ...)`: Extract column values as a vector, by name or index.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> pull(wt)\n ```\n :::\n\n\n- `select(.data, ...)`: Extract columns as a table.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> select(mpg, wt)\n ```\n :::\n\n\n- `relocate(.data, ..., .before = NULL, .after = NULL)`: Move columns to new position.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> relocate(mpg, cyl, after = last_col())\n ```\n :::\n\n\n#### Use these helpers with `select()` and `across()`\n\n\n::: {.cell}\n\n```{.r .cell-code}\nmtcars |> select(mpg:cyl)\n```\n:::\n\n\n- `contains(match)`\n- `num_range(prefix, range)`\n- `:`, e.g., `mpg:cyl`\n- `ends_with(match)`\n- `all_of(x)` or `any_of(x, ..., vars)`\n- `!`, e.g., `!gear`\n- `starts_with(match)`\n- `matches(match)`\n- `everything()`\n\n### Manipulate Multiple Variables at Once\n\n\n::: {.cell}\n\n```{.r .cell-code}\ndf <- tibble(x_1 = c(1, 2), x_2 = c(3, 4), y = c(4, 5))\n```\n:::\n\n\n- `across(.cols, .fun, ..., .name = NULL)`: summarize or mutate multiple columns in the same way.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n df |> summarize(across(everything(), mean))\n ```\n :::\n\n\n- `c_across(.cols)`: Compute across columns in row-wise data.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n df |> \n rowwise() |>\n mutate(x_total = sum(c_across(1:2)))\n ```\n :::\n\n\n### Make New Variables\n\nApply **vectorized functions** to columns.\nVectorized functions take vectors as input and return vectors of the same length as output (see Vectorized Functions).\n\n- `mutate(.data, ..., .keep = \"all\", .before = NULL, .after = NULL)`: Compute new column(s).\n Also `add_column()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> mutate(gpm = 1 / mpg)\n mtcars |> mutate(mtcars, gpm = 1 / mpg, .keep = \"none\")\n ```\n :::\n\n\n- `rename(.data, ...)`: Rename columns.\n Use `rename_with()` to rename with a function.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |> rename(miles_per_gallon = mpg)\n ```\n :::\n\n\n\n\n## Vectorized Functions\n\n### To Use with `mutate()`\n\n`mutate()` applies vectorized functions to columns to create new columns.\nVectorized functions take vectors as input and return vectors of the same length as output.\n\n### Offset\n\n- `dplyr::lag()`: offset elements by 1\n- `dplyr::lead()`: offset elements by -1\n\n### Cumulative Aggregate\n\n- `dplyr::cumall()`: cumulative `all()`\n- `dply::cumany()`: cumulative `any()`\n- `cummax()`: cumulative `max()`\n- `dplyr::cummean()`: cumulative `mean()`\n- `cummin()`: cumulative `min()`\n- `cumprod()`: cumulative `prod()`\n- `cumsum()`: cumulative `sum()`\n\n### Ranking\n\n- `dplyr::cume_dist()`: proportion of all values \\<=\n- `dplyr::dense_rank()`: rank with ties = min, no gaps\n- `dplyr::min_rank()`: rank with ties = min\n- `dplyr::ntile()`: bins into n bins\n- `dplyr::percent_rank()`: `min_rank()` scaled to \\[0,1\\]\n- `dplyr::row_number()`: rank with ties = \"first\"\n\n### Math\n\n- `+`, `-`, `/`, `^`, `%/%`, `%%`: arithmetic ops\n- `log()`, `log2()`, `log10()`: logs\n- `<`, `<=`, `>`, `>=`, `!=`, `==`: logical comparisons\n- `dplyr::between()`: x \\>= left & x \\<= right\n- `dplyr::near()`: safe `==` for floating point numbers\n\n### Miscellaneous\n\n- `dplyr::case_when()`: multi-case `if_else()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n starwars |>\n mutate(type = case_when(\n height > 200 | mass > 200 ~ \"large\",\n species == \"Droid\" ~ \"robot\",\n TRUE ~ \"other\"\n ))\n ```\n :::\n\n\n- `dplyr::coalesce()`: first non-NA values by element across a set of vectors\n\n- `dplyr::if_else()`: element-wise if() + else()\n\n- `dplyr::na_if()`: replace specific values with NA\n\n- `pmax()`: element-wise max()\n\n- `pmin()`: element-wise min()\n\n## Summary Functions\n\n### To Use with `summarize()`\n\n`summarize()` applies summary functions to columns to create a new table.\nSummary functions take vectors as input and return single values as output.\n\n### Count\n\n- `dplyr::n()`: number of values/rows\n- `dplyr::n_distinct()`: \\# of uniques\n- `sum(!is.na())`: \\# of non-NAs\n\n### Position\n\n- `mean()`: mean, also `mean(!is.na())`\n- `median()`: median\n\n### Logical\n\n- `mean()`: proportion of TRUEs\n- `sum()`: \\# of TRUEs\n\n### Order\n\n- `dplyr::first()`: first value\n- `dplyr::last()`: last value\n- `dplyr::nth()`: value in the nth location of vector\n\n### Rank\n\n- `quantile()`: nth quantile\n- `min()`: minimum value\n- `max()`: maximum value\n\n### Spread\n\n- `IQR()`: Inter-Quartile Range\n- `mad()`: median absolute deviation\n- `sd()`: standard deviation\n- `var()`: variance\n\n## Row Names\n\nTidy data does not use rownames, which store a variable outside of the columns.\nTo work with the rownames, first move them into a column.\n\n- `tibble::rownames_to_column()`: Move row names into col.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n a <- rownames_to_column(mtcars, var = \"C\")\n ```\n :::\n\n\n- `tibble::columns_to_rownames()`: Move col into row names.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n column_to_rownames(a, var = \"C\")\n ```\n :::\n\n\n- Also `tibble::has_rownames()` and `tibble::remove_rownames()`.\n\n## Combine Tables\n\n\n::: {.cell}\n\n```{.r .cell-code}\nx <- tribble(\n ~A, ~B, ~C,\n \"a\", \"t\", 1,\n \"b\", \"u\", 2,\n \"c\", \"v\", 3\n)\n\ny <- tribble(\n ~A, ~B, ~D,\n \"a\", \"t\", 3,\n \"b\", \"u\", 2,\n \"d\", \"w\", 1\n)\n```\n:::\n\n\n### Combine Variables\n\n- `bind_cols(..., .name_repair)`: Returns tables placed side by side as a single table. Column lengths must be equal. Columns will NOT be matched by id (to do that look at Relational Data below), so be sure to check that both tables are ordered the way you want before binding.\n\n### Combine Cases\n\n- `bind_rows(..., .id = NULL)`: Returns tables one on top of the other as a single table. Set `.id` to a column name to add a column of the original table names.\n\n### Relational Data\n\nUse a **\"Mutating Join\"** to join one table to columns from another, matching values with the rows that the correspond to.\nEach join retains a different combination of values from the tables.\n\n- `left_join(x, y, by = NULL, copy = FALSE, suffix = c(\".x\", \".y\"), ..., keep = FALSE, na_matches = \"na\")`: Join matching values from `y` to `x`.\n- `right_join(x, y, by = NULL, copy = FALSE, suffix = c(\".x\", \".y\"), ..., keep = FALSE, na_matches = \"na\")`: Join matching values from `x` to `y`.\n- `inner_join(x, y, by = NULL, copy = FALSE, suffix = c(\".x\", \".y\"), ..., keep = FALSE, na_matches = \"na\")`: Join data. retain only rows with matches.\n- `full_join(x, y, by = NULL, copy = FALSE, suffix = c(\".x\", \".y\"), ..., keep = FALSE, na_matches = \"na\")`: Join data. Retain all values, all rows.\n\nUse a **\"Filtering Join\"** to filter one table against the rows of another.\n\n- `semi_join(x, y, by = NULL, copy = FALSE, ..., na_matches = \"na\")`: Return rows of `x` that have a match in `y`. Use to see what will be included in a join.\n- `anti_join(x, y, by = NULL, copy = FALSE, ..., na_matches = \"na\")`: Return rows of `x` that do not have a match in `y`. Use to see what will not be included in a join.\n\nUse a **\"Nest Join\"** to inner join one table to another into a nested data frame.\n\n- `nest_join(x, y, by = NULL, copy = FALSE, keep = FALSE, name = NULL, ...)`: Join data, nesting matches from `y` in a single new data frame column.\n\n### Column Matching for Joins\n\n- Use `by = c(\"col1\", \"col2\", ...)` to specify one or more common columns to match on.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n left_join(x, y, by = \"A\")\n ```\n :::\n\n\n- Use a named vector, `by = c(\"col1\" = \"col2\")`, to match on columns that have different names in each table.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n left_join(x, y, by = c(\"C\" = \"D\"))\n ```\n :::\n\n\n- Use `suffix` to specify the suffix to give to unmatched columns that have the same name in both tables.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n left_join(x, y, by = c(\"C\" = \"D\"), suffix = c(\"1\", \"2\"))\n ```\n :::\n\n\n### Set Operations\n\n- `intersect(x, y, ...)`: Rows that appear in both `x` and `y`.\n- `setdiff(x, y, ...)`: Rows that appear in `x` but not `y`.\n- `union(x, y, ...)`: Rows that appear in x or y, duplicates removed. `union_all()` retains duplicates.\n- Use `setequal()` to test whether two data sets contain the exact same rows (in any order).\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [dplyr.tidyverse.org](https://dplyr.tidyverse.org).\n\nUpdated: 2023-06.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"dplyr\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.1.2'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", "supporting": [], "filters": [ "rmarkdown/pagebreak.lua" diff --git a/_freeze/html/data-visualization/execute-results/html.json b/_freeze/html/data-visualization/execute-results/html.json index ab409a2d..98ae6048 100644 --- a/_freeze/html/data-visualization/execute-results/html.json +++ b/_freeze/html/data-visualization/execute-results/html.json @@ -1,7 +1,7 @@ { - "hash": "6b210577c339cd80b4e7100e3314d1f2", + "hash": "012926f5b067ea865338dfff9e104a44", "result": { - "markdown": "---\ntitle: \"Data visualization with ggplot2 :: Cheat Sheet\"\ndescription: \" \"\nimage: \"images/logo-ggplot2.png\"\nimage-alt: \"Hex logo for ggplot2 - Six points following an overall increasing trend filled with colors going from light blue to dark blue, connected with a black line, on a light gray background with white grid lines.\"\nexecute:\n eval: true\n output: false\n warning: false\n---\n\n::: {.cell .column-margin}\n\"Hex\n

\n

Download PDF

\n\n
\n

Translations (PDF)

\n* Chinese\n* Dutch\n* French\n* German\n* Japanese\n* Portuguese\n* Spanish\n* Turkish\n* Vietnamese\n:::\n\n\n\n\n## Basics\n\n**ggplot2** is based on the **grammar of graphics**, the idea that you can build every graph from the same components: a **data** set, a **coordinate system**, and **geoms**---visual marks that represent data points.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(ggplot2)\n```\n:::\n\n\n\n\nTo display values, map variables in the data to visual properties of the geom (**aesthetics**) like **size**, **color**, and **x** and **y** locations.\n\nComplete the template below to build a graph.\n\n``` \nggplot(data = ) +\n (mapping = aes(),\n stat = ,\n position = ) +\n +\n +\n +\n \n```\n\nData, a Geom Function, and Aes Mappings are required.\nStat, Position, and the Coordinate, Facet, Scale, and Theme functions are not required and will supply sensible defaults.\n\n- `ggplot(data = mpg, aes(x = cty, y = hwy))`: Begins a plot that you finish by adding layers to.\n Add one geom function per layer.\n\n- `last_plot()`: Returns the last plot.\n\n- `ggsave(\"plot.png\", width = 5, height = 5)`: Saves last plot as 5' x 5' file named \"plot.png\" in working directory.\n Matches file type to file extension.\n\n## Aes\n\nCommon aesthetic values.\n\n- `color` and `fill`: String (`\"red\"`, `\"#RRGGBB\"`).\n\n- `linetype`: Integer or string (0 = `\"blank\"`, 1 = `\"solid\"`, 2 = `\"dashed\"`, 3 = `\"dotted\"`, 4 = `\"dotdash\"`, 5 = `\"longdash\"`, 6 = `\"twodash\"`).\n\n- `lineend`: String (`\"round\"`, `\"butt\"`, or `\"square\"`).\n\n- `linejoin`: String (`\"round\"`, `\"mitre\"`, or `\"bevel\"`).\n\n- `size`: Integer (line width in mm).\n\n- `shape`: Integer/shape name or a single character (`\"a\"`).\n\n - `shape` integer/name pairs: 0 = `\"square open\"`, 1 = `\"circle open\"`, 2 = `\"triangle open\"`, 3 = `\"plus\"`, 4 = `\"cross\"`, 5 = `\"diamond open\"`, 6 = `\"triangle down open\"`, 7 = `\"square cross\"`, 8 = `\"asterisk\"`, 9 = `\"diamond plus\"`, 10 = `\"circle plus\"`, 11 = `\"star\"`, 12 = `\"square plus\"`, 13 = `\"circle cross\"`, 14 = `\"square triangle\"`, 15 = `\"square\"`, 16 = `\"circle\"`, 17 = `\"triangle\"`, 18 = `\"diamond\"`, 19 = `\"circle small\"`, 20 = `\"bullet\"`, 21 = `\"circle filled\"`, 22 = `\"square filled\"`, 23 = `\"diamond filled\"`, 24 = `\"triangle filled\"`, 25 = `\"triangle down filled\"`\n\n## Geoms\n\nUse a geom function to represent data points, use the geom's aesthetic properties to represent variables.\nEach function returns a layer.\n\n### Graphical Primitives\n\n\n::: {.cell}\n\n```{.r .cell-code}\na <- ggplot(economics, aes(date, unemploy))\n\nb <- ggplot(seals, aes(x = long, y = lat))\n```\n:::\n\n\n- `a + geom_blank()` and `a + expand_limits()`: Ensure limits include values across all plots.\n\n- `b + geom_curve(aes(yend = lat + 1, xend = long + 1), curvature = 1)`: Draw a curved line from `(x, y)` to `(xend, yend)`.\n `aes()` arguments: `x`, `xend`, `y`, `yend`, `alpha`, `angle`, `color`, `curvature`, `linetype`, `size`.\n\n- `a + geom_path(lineend = \"butt\", linejoin = \"round\", linemitre = 1)`: Connect observations in the order they appear.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `group`, `linetype`, `size`.\n\n- `a + geom_polygon(aes(alpha = 50))`: Connect points into polygons.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `group`, `subgroup`, `linetype`, `size`.\n\n- `b + geom_rect(aes(xmin = long, ymin = lat, xmax = long + 1, ymax = lat + 1))`: Draw a rectangle by connecting four corners (`xmin`, `xmax`, `ymin`, `ymax`).\n `aes()` arguments: `xmax`, `xmin`, `ymax`, `ymin`, `alpha`, `color`, `fill`, `linetype`, `size`.\n\n- `a + geom_ribbon(aes(ymin = unemploy - 900, ymax = unemploy + 900)`: For each `x`, plot an interval from `ymin` to `ymax`.\n `aes()` arguments: `x`, `ymax`, `ymin`, `alpha`, `color`, `fill`, `group`, `linetype`, `size`.\n\n#### Line Segments\n\nCommon aesthetics: `x`, `y`, `alpha`, `color`, `linetype`, `size`.\n\n- `b + geom_abline(aes(intercept = 0, slope = 1))`: Draw a diagonal reference line with a given `slope` and `intercept`.\n\n- `b + geom_hline(aes(yintercept = lat))`: Draw a horizontal reference line with a given `yintercept`.\n\n- `b + geom_vline(aes(xintercept = long))`: Draw a vertical reference line with a given `xintercept`.\n\n- `b + geom_segment(aes(yend = lat + 1, xend = long + 1))`: Draw a straight line from `(x, y)` to `(xend, yend)`.\n\n- `b + geom_spoke(aes(angle = 1:1155, radius = 1))`: Draw line segments using polar coordinates (`angle` and `radius`).\n\n### One Variable - Continuous\n\n\n::: {.cell}\n\n```{.r .cell-code}\nc <- ggplot(mpg, aes(hwy))\nc2 <- ggplot(mpg)\n```\n:::\n\n\n- `c + geom_area(stat = \"bin\")`: Draw an area plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `linetype`, `size`.\n\n- `c + geom_density(kernel = \"gaussian\")`: Compute and draw kernel density estimates.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `group`, `linetype`, `size`, `weight`.\n\n- `c + geom_dotplot()`: Draw a dot plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`.\n\n- `c + geom_freqpoly()`: Draw a frequency polygon.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `group`, `linetype`, `size`.\n\n- `c + geom_histogram(binwidth = 5)`: Draw a histogram.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `linetype`, `size`, `weight`.\n\n- `c2 + geom_qq(aes(sample = hwy))`: Draw a quantile-quantile plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `linetype`, `size`, `weight`.\n\n### One Variable - Discrete\n\n\n::: {.cell}\n\n```{.r .cell-code}\nd <- ggplot(mpg, aes(fl))\n```\n:::\n\n\n- `d + geom_bar()`: Draw a bar chart. `aes()` arguments: `x`, `alpha`, `color`, `fill`, `linetype`, `size`, `weight`.\n\n### Two Variables - Both Continuous\n\n\n::: {.cell}\n\n```{.r .cell-code}\ne <- ggplot(mpg, aes(cty, hwy))\n```\n:::\n\n\n- `e + geom_label(aes(label = cty), nudge_x = 1, nudge_y = 1)`: Add text with a rectangle background.\n `aes()` arguments: - `x`, `y`, `label`, `alpha`, `angle`, `color`, `family`, `fontface`, `hjust`, `lineheight`, `size`, `vjust`.\n\n- `e + geom_point()`: Draw a scatter plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `shape`, `size`, `stroke`.\n\n- `e + geom_quantile()`: Fit and draw quantile regression for the plot data.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `group`, `linetype`, `size`, `weight`.\n\n- `e + geom_rug(sides = \"bl\")`: Draw a rug plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `linetype`, `size`.\n\n- `e + geom_smooth(method = lm)`: Plot smoothed conditional means.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `group`, `linetype`, `size`, `weight`.\n\n- `e + geom_text(aes(label = cty), nudge_x = 1, nudge_y = 1)`: Add text to a plot.\n `aes()` arguments: `x`, `y`, `label`, `alpha`, `angle`, `color`, `family`, `fontface`, `hjust`, `lineheight`, `size`, `vjust`.\n\n### Two Variables - One Discrete, One Continuous\n\n\n::: {.cell}\n\n```{.r .cell-code}\nf <- ggplot(mpg, aes(class, hwy))\n```\n:::\n\n\n- `f + geom_col()`: Draw a bar plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `group`, `linetype`, `size`.\n\n- `f + geom_boxplot()`: Draw a box plot.\n `aes()` arguments: `x`, `y`, `lower`, `middle`, `upper`, `ymax`, `ymin`, `alpha`, `color`, `fill`, `group`, `linetype`, `shape`, `size`, `weight`.\n\n- `f + geom_dotplot(binaxis =\"y\", stackdir = \"center\")`: Draw a dot plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `group`.\n\n- `f + geom_violin(scale = \"area\")`: Draw a violin plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `group`, `linetype`, `size`, `weight`.\n\n### Two Variables - Both Discrete\n\n\n::: {.cell}\n\n```{.r .cell-code}\ng <- ggplot(diamonds, aes(cut, color))\n```\n:::\n\n\n- `g + geom_count()`: Plot a count of points in an area to address over plotting.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `shape`, `size`, `stroke`.\n\n- `e + geom_jitter(height = 2, width = 2)`: Jitter points in a plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `shape`, `size`.\n\n### Two Variables - Continuous Bivariate Distribution\n\n\n::: {.cell}\n\n```{.r .cell-code}\nh <- ggplot(diamonds, aes(carat, price))\n```\n:::\n\n\n- `h + geom_bin2d(binwidth = c(0.25, 500))`: Draw a heatmap of 2D rectangular bin counts.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `linetype`, `size`, `weight`.\n\n- `h + geom_density_2d()`: Plot contours from 2D kernel density estimation.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `group`, `linetype`, `size`.\n\n- `h + geom_hex()`: Draw a heatmap of 2D hexagonal bin counts.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `size`.\n\n### Two Variables - Continuous Function\n\n\n::: {.cell}\n\n```{.r .cell-code}\ni <- ggplot(economics, aes(date, unemploy))\n```\n:::\n\n\n- `i + geom_area()`: Draw an area plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `linetype`, `size`.\n\n- `i + geom_line()`: Connect data points, ordered by the x axis variable.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `group`, `linetype`, `size`.\n\n- `i + geom_step(direction = \"hv\"`: Draw a stairstep plot. `aes()` arguments: `x`, `y`, `alpha`, `color`, `group`, `linetype`, `size`.\n\n### Two Variables - Visualizing Error\n\n\n::: {.cell}\n\n```{.r .cell-code}\ndf <- data.frame(grp = c(\"A\", \"B\"), fit = 4:5, se = 1:2)\nj <- ggplot(df, aes(grp, fit, ymin = fit - se, ymax = fit + se))\n```\n:::\n\n\n- `j + geom_crossbar(fatten = 2)`: Draw a crossbar.\n `aes()` arguments: `x`, `y`, `ymax`, `ymin`, `alpha`, `color`, `fill`, `group`, `linetype`, `size`.\n\n- `j + geom_errorbar()`: Draw an errorbar.\n Also `geom_errorbarh()`.\n `aes()` arguments: `x`, `ymax`, `ymin`, `alpha`, `color`, `group`, `linetype`, `size`, `width`.\n\n- `j + geom_linerange()`: Draw a line range.\n `aes()` arguments: `x`, `ymin`, `ymax`, `alpha`, `color`, `group`, `linetype`, `size`.\n\n- `j + geom_pointrange()`: Draw a point range.\n `aes()` arguments: `x`, `y`, `ymin`, `ymax`, `alpha`, `color`, `fill`, `group`, `linetype`, `shape`, `size`.\n\n### Two Variables - Maps\n\n\n::: {.cell}\n\n```{.r .cell-code}\nmurder_data <- data.frame(\n murder = USArrests$Murder, \n state = tolower(rownames(USArrests))\n)\nmap <- map_data(\"state\")\nk <- ggplot(murder_data, aes(fill = murder))\n```\n:::\n\n\n- `k + geom_map(aes(map_id = state), map = map) + expand_limits(x = map$long, y = map$lat)`: Draw polygons as a map. `aes()` arguments: `map_id`, `alpha`, `color`, `fill`, `linetype`, `size`.\n\n### Three Variables\n\n\n::: {.cell}\n\n```{.r .cell-code}\nseals$z <- with(seals, sqrt(delta_long^2 + delta_lat^2))\nl <- ggplot(seals, aes(long, lat))\n```\n:::\n\n\n- `l + geom_contour(aes(z = z))`: Draw 2D contour plot.\n `aes()` arguments: `x`, `y`, `z`, `alpha`, `color`, `group`, `linetype`, `size`, `weight`.\n\n- `l + geom_contour_filled(aes(fill = z))`: Draw 2D contour plot with the space between lines filled.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `group`, `linetype`, `size`, `subgroup`.\n\n- `l + geom_raster(aes(fill = z), hjust = 0.5, vjust = 0.5, interpolate = FALSE)`: Draw a raster plot.\n `aes()` arguments: `x`, `y`, `alpha`, `fill`.\n\n- `l + geom_tile(aes(fill = z))`: Draw a tile plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `linetype`, `size`, `width`.\n\n\n\n## Stats\n\nAn alternative way to build a layer.\n\nA stat builds new variables to plot (e.g., count, prop).\n\nVisualize a stat by changing the default stat of a geom function, `geom_bar(stat = \"count\")`, or by using a stat function, `stat_count(geom = \"bar\")`, which calls a default geom to make a layer (equivalent to a geom function).\nUse `..name..` syntax to map stat variables to aesthetics.\n\n\n::: {.cell}\n\n```{.r .cell-code}\ni + stat_density_2d(aes(fill = ..level..), geom = \"polygon\")\n```\n:::\n\n\nIn this example, `\"polygon\"` is the geom to use, `stat_density_2d()` is the stat function, `aes()` contains the geom mappings, and `..level..` is the variable created by stat.\n\n- `c + stat_bin(binwidth = 1, boundary = 10)`: `x`, `y` \\| `..count..`, `..ncount..`, `..density..`, `..ndensity..`\n\n- `c + stat_count(width = 1)`: `x`, `y` \\| `..count..`, `..density..`\n\n- `c + stat_density(adjust = 1, kernel = \"gaussian\")`: `x`, `y` \\| `..count..`, `..density..`, `..scaled..`\n\n- `e + stat_bin_2d(bins = 30, drop = T)`: `x`, `y`, `fill` \\| `..count..`, `..density..`\n\n- `e + stat_bin_hex(bins =30)`: `x`, `y`, `fill` \\| `..count..`, `..density..`\n\n- `e + stat_density_2d(contour = TRUE, n = 100)`: `x`, `y`, `color`, `size` \\| `..level..`\n\n- `e + stat_ellipse(level = 0.95, segments = 51, type = \"t\")`\n\n- `l + stat_contour(aes(z = z))`: `x`, `y`, `z`, `order` \\| `..level..`\n\n- `l + stat_summary_hex(aes(z = z), bins = 30, fun = max)`: `x`, `y`, `z`, `fill` \\| `..value..`\n\n- `l + stat_summary_2d(aes(z = z), bins = 30, fun = mean)`: `x`, `y`, `z`, `fill` \\| `..value..`\n\n- `f + stat_boxplot(coef = 1.5)`: `x`, `y` \\| `..lower..`, `..middle..`, `..upper..`, `..width..`, `..ymin..`, `..ymax..`\n\n- `f + stat_ydensity(kernel = \"gaussian\", scale = \"area\")`: `x`, `y` \\| `..density..`, `..scaled..`, `..count..`, `..n..`, `..violinwidth..`, `..width..`\n\n- `e + stat_ecdf(n = 40)`: `x`, `y` \\| `..x..`, `..y..`\n\n- `e + stat_quantile(quantiles = c(0.1, 0.9), formula = y ~ log(x), method = \"rq\")`: `x`, `y` \\| `..quantile..`\n\n- `e + stat_smooth(method = \"lm\", formula = y ~ x, se = T, level = 0.95)`: `x`, `y` \\| `..se..`, `..x..`, `..y..`, `..ymin..`, `..ymax..`\n\n- `ggplot() + xlim(-5, 5) + stat_function(fun = dnorm, n = 20, geom = \"point\")`: `x` \\| `..x..`, `..y..`\n\n- `ggplot() + stat_qq(aes(sample = 1:100))`: `x`, `y`, `sample` \\| `..sample..`, `..theoretical..`\n\n- `e + stat_sum()`: `x`, `y`, `size` \\| `..n..`, `..prop..`\n\n- `e + stat_summary(fun.data = \"mean_cl_boot\")`\n\n- `h + stat_summary_bin(fun = \"mean\", geom = \"bar\")`\n\n- `e + stat_identity()`\n\n- `e + stat_unique()`\n\n## Scales\n\nOverride defaults with **scales** package.\n\n**Scales** map data values to the visual values of an aesthetic.\nTo change a mapping, add a new scale.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nn <- d + geom_bar(aes(fill = fl))\n\nn + scale_fill_manual(\n value = c(),\n limits = c(), \n breaks = c(),\n name = \"fuel\", \n labels = c(\"D\", \"E\", \"P\", \"R\")\n)\n```\n:::\n\n\nIn this example, `scale_` specifies a scale function, `fill` is the aesthetic to adjust, and `manual` is the prepackaged scale to use.\n\n`values` contains scale-specific arguments, `limits` specifies the range of values to include in mappings, `breaks` specifies the breaks to use in legend/axis, and `name` and `labels` specify the title and labels to use in the legend/axis.\n\n### General Purpose Scales\n\nUse with most aesthetics.\n\n- `scale_*_continuous()`: Map continuous values to visual ones.\n\n- `scale_*_discrete()`: Map discrete values to visual ones.\n\n- `scale_*_binned()`: Map continuous values to discrete bins.\n\n- `scale_*_identity()`: Use data values as visual ones.\n\n- `scale_*_manual(values = c())`: Map discrete values to manually chosen visual ones.\n\n- `scale_*_date(date_labels = \"%m/%d\", date_breaks = \"2 weeks\")`: Treat data values as dates.\n\n- `scale_*_datetime()`: Treat data values as date times.\n Same as `scale_*_date()`.\n See `?strptime` for label formats.\n\n### X & Y Location Scales\n\nUse with x or y aesthetics (x shown here).\n\n- `scale_x_log10()`: Plot `x` on log10 scale.\n\n- `scale_x_reverse()`: Reverse the direction of the x axis.\n\n- `scale_x_sqrt()`: Plot `x` on square root scale.\n\n### Color and Fill Scales (Discrete)\n\n- `n + scale_fill_brewer(palette = \"Blues\")`: Use color scales from ColorBrewer.\n For palette choices `RColorBrewer::display.brewer.all()`.\n\n- `n + scale_fill_grey(start = 0.2, end = 0.8, na.value = \"red\")`: Use a grey gradient color scale.\n\n### Color and Fill Scales (Continuous)\n\n\n::: {.cell}\n\n```{.r .cell-code}\no <- c + geom_dotplot(aes(fill = ..x..))\n```\n:::\n\n\n- `o + scale_fill_distiller(palette = \"Blues\")`: Interpolate a palette into a continuous scale.\n\n- `o + scale_fill_gradient(low = \"red\", high = \"yellow\")`: Create a two color gradient.\n\n- `o + scale_fill_gradient2(low = \"red\", high = \"blue\", mid = \"white\", midpoint = 25)`: Create a diverging color gradient.\n\n- `o + scale_fill_gradientn(colors = topo.colors(6))`: Create a n-color gradient.\n Also `rainbow()`, `heat.colors()`, `terrain.colors()`, `cm.colors()`, `RColorBrewer::brewer.pal()`.\n\n### Shape and Size Scales\n\n\n::: {.cell}\n\n```{.r .cell-code}\np <- e + geom_point(aes(shape = fl, size = cyl))\n```\n:::\n\n\n- `p + scale_shape() + scale_size()`: Map discrete values to shape and size aesthetics.\n\n- `p + scale_shape_manual(values = c(3:7))`: Map discrete values to specified shape values.\n\n- `p + scale_radius(range = c(1,6))`: Map values to a shape's radius.\n\n- `p + scale_size_area(max_size = 6)`: Like `scale_size()` but maps zero values to zero size.\n\nShapes used here are the same as the ones listed in the Aes section.\n\n## Coordinate Systems\n\n\n::: {.cell}\n\n```{.r .cell-code}\nu <- d + geom_bar()\n```\n:::\n\n\n- `u + coord_cartesian(xlim = c(0, 5))`: `xlim`, `ylim`.\n The default Cartesian coordinate system.\n\n- `u + coord_fixed(ratio = 1/2)`: `ratio`, `xlim`, `ylim`.\n Cartesian coordinates with fixed aspect ration between x and y units.\n\n- `ggplot(mpg, aes(y = fl)) + geom_bar()`: Flip Cartesian coordinates by switching x and y aesthetic mappings.\n\n- `u + coord_polar(theta = \"x\", direction = 1)`: `theta`, `start`, `direction`.\n Polar coordinates.\n\n- `u + coord_trans(y = \"sqrt\")`: `x`, `y`, `xlim`, `ylim`.\n Transformed Cartesian coordinates.\n Set `xtrans` and `ytrans` to the name of a window function.\n\n- `π + coord_quickmap(); π + coord_map(projection = \"ortho\", orientation = c(41, -74, 0))`: `projection`, `xlim`, `ylim`.\n Map projections from the **mapproj** packages (`mercator` (default), `azequalarea`, `lagrange`, etc.).\n\n## Position Adjustments\n\nPosition adjustments determine how to arrange geoms that would otherwise occupy the same space.\n\n\n::: {.cell}\n\n```{.r .cell-code}\ns <- ggplot(mpg, aes(fl, fill = drv))\n```\n:::\n\n\n- `s + geom_bar(position = \"dodge\")`: Arrange elements side by side.\n\n- `s + geom_bar(position = \"fill\")`: Stack elements on top of one another, normalize height.\n\n- `e + geom_point(position = \"jitter\")`: Add random noise to X and Y position of each element to avoid over plotting.\n\n- `e + geom_label(position = \"nudge\")`: Nudge labels away from points.\n\n- `s + geom_bar(position = \"stack\")`: Stack elements on top of one another.\n\nEach position adjustment can be recast as a function with manual `width` and `height` arguments:\n\n\n::: {.cell}\n\n```{.r .cell-code}\ns + geom_bar(position = position_dodge(width = 1))\n```\n:::\n\n\n## Themes\n\n- `u + theme_bw()`: White background with grid lines.\n\n- `u + theme_gray()`: Grey background with white grid lines (default theme).\n\n- `u + theme_dark()`: Dark grey background and grid lines for contrast.\n\n- `u + theme_classic()`: No grid lines.\n\n- `u + theme_light()`: Light grey axes and grid lines.\n\n- `u + theme_linedraw()`: Uses only black lines.\n\n- `u + theme_minimal()`: Minimal theme.\n\n- `u + theme_void()`: Empty theme.\n\n- `u + theme()`: Customize aspects of the theme such as axis, legend, panel, and facet properties.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n r + ggtitle(\"Title\") + theme(plot.title.postion = \"plot\")\n \n r + theme(panel.background = element_rect(fill = \"blue\"))\n ```\n :::\n\n\n## Faceting\n\nFacets divide a plot into subplots based on the values of one or more discrete variables.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nt <- ggplot(mpg, aes(cty, hwy)) + geom_point()\n```\n:::\n\n\n- `t + facet_grid(cols = vars(fl))`: Facet into a column based on fl.\n\n- `t + facet_grid(rows = vars(year))`: Facet into rows based on year.\n\n- `t + facet_grid(rows = vars(year), cols = vars(fl))`: Facet into both rows and columns.\n\n- `t_facet_wrap(vars(fl))`: Wrap facets into a rectangular layout.\n\n- `t + facet_grid(rows = vars(drv), cols = vars(fl), scales = \"free\")`: Set **scales** to let axis limits vary across facets.\n Also `\"free_x\"` for x axis limits adjust to individual facets and `\"free_y\"` for y axis limits adjust to individual facets.\n\nSet **labeller** to adjust facet label:\n\n- `t + facet_grid(cols = vars(fl), labeller = label_both)`: Labels each facet as \"fl: c\", \"fl: d\", etc.\n\n- `t + facet_grid(rows = vars(fl), labeller = label_bquote(alpha ^ .(fl)))`: Labels each facet as \"𝛼^c^\", \"𝛼^d^\", etc.\n\n## Labels and Legends\n\nUse `labs()` to label elements of your plot.\n\n``` \nt + labs(x = \"New x axis label\", \n y = \"New y axis label\",\n title =\"Add a title above the plot\",\n subtitle = \"Add a subtitle below title\",\n caption = \"Add a caption below plot\",\n alt = \"Add alt text to the plot\",\n = \"New legend title\")\n```\n\n- `t + annotate(geom = \"text\", x = 8, y = 9, label = \"A\")`: Places a geom with manually selected aesthetics.\n\n- `p + guides(x = guide_axis(n.dodge = 2))`: Avoid crowded or overlapping labels with `guide_axis(n.dodge or angle)`.\n\n- `n + guides(fill = \"none\")`: Set legend type for each aesthetic: `colorbar`, `legend`, or `none` (no legend).\n\n- `n + theme(legend.position = \"bottom\")`: Place legend at \"bottom\", \"top\", \"left\", or \"right\".\n\n- `n + scale_fill_discrete(name = \"Title\", labels = c(\"A\", \"B\", \"C\", \"D\", \"E\"))`: Set legend title and labels with a scale function.\n\n## Zooming\n\n- `t + coord_cartesian(xlim = c(0, 100), ylim = c(10,20))`: Zoom without clipping (preferred).\n\n- `t + xlim(0, 100) + ylim(10, 20)` or `t + scale_x_continuous(limits = c(0, 100)) + scale_y_continuous(limits = c(0, 100))`: Zoom with clipping (removes unseen data points).\n", + "markdown": "---\ntitle: \"Data visualization with ggplot2 :: Cheat Sheet\"\ndescription: \" \"\nexecute:\n eval: true\n output: false\n warning: false\n---\n\n::: {.cell .column-margin}\n\"Hex\n

\n

Download PDF

\n\"\"/\n
\n

Translations (PDF)

\n* Chinese\n* Dutch\n* French\n* German\n* Japanese\n* Portuguese\n* Spanish\n* Turkish\n* Vietnamese\n:::\n\n\n\n\n## Basics\n\n**ggplot2** is based on the **grammar of graphics**, the idea that you can build every graph from the same components: a **data** set, a **coordinate system**, and **geoms**---visual marks that represent data points.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(ggplot2)\n```\n:::\n\n\n\n\nTo display values, map variables in the data to visual properties of the geom (**aesthetics**) like **size**, **color**, and **x** and **y** locations.\n\nComplete the template below to build a graph.\n\n``` \nggplot(data = ) +\n (mapping = aes(),\n stat = ,\n position = ) +\n +\n +\n +\n \n```\n\nData, a Geom Function, and Aes Mappings are required.\nStat, Position, and the Coordinate, Facet, Scale, and Theme functions are not required and will supply sensible defaults.\n\n- `ggplot(data = mpg, aes(x = cty, y = hwy))`: Begins a plot that you finish by adding layers to.\n Add one geom function per layer.\n\n- `last_plot()`: Returns the last plot.\n\n- `ggsave(\"plot.png\", width = 5, height = 5)`: Saves last plot as 5' x 5' file named \"plot.png\" in working directory.\n Matches file type to file extension.\n\n## Aes\n\nCommon aesthetic values.\n\n- `color` and `fill`: String (`\"red\"`, `\"#RRGGBB\"`).\n\n- `linetype`: Integer or string (0 = `\"blank\"`, 1 = `\"solid\"`, 2 = `\"dashed\"`, 3 = `\"dotted\"`, 4 = `\"dotdash\"`, 5 = `\"longdash\"`, 6 = `\"twodash\"`).\n\n- `lineend`: String (`\"round\"`, `\"butt\"`, or `\"square\"`).\n\n- `linejoin`: String (`\"round\"`, `\"mitre\"`, or `\"bevel\"`).\n\n- `size`: Integer (line width in mm).\n\n- `shape`: Integer/shape name or a single character (`\"a\"`).\n\n - `shape` integer/name pairs: 0 = `\"square open\"`, 1 = `\"circle open\"`, 2 = `\"triangle open\"`, 3 = `\"plus\"`, 4 = `\"cross\"`, 5 = `\"diamond open\"`, 6 = `\"triangle down open\"`, 7 = `\"square cross\"`, 8 = `\"asterisk\"`, 9 = `\"diamond plus\"`, 10 = `\"circle plus\"`, 11 = `\"star\"`, 12 = `\"square plus\"`, 13 = `\"circle cross\"`, 14 = `\"square triangle\"`, 15 = `\"square\"`, 16 = `\"circle\"`, 17 = `\"triangle\"`, 18 = `\"diamond\"`, 19 = `\"circle small\"`, 20 = `\"bullet\"`, 21 = `\"circle filled\"`, 22 = `\"square filled\"`, 23 = `\"diamond filled\"`, 24 = `\"triangle filled\"`, 25 = `\"triangle down filled\"`\n\n## Geoms\n\nUse a geom function to represent data points, use the geom's aesthetic properties to represent variables.\nEach function returns a layer.\n\n### Graphical Primitives\n\n\n::: {.cell}\n\n```{.r .cell-code}\na <- ggplot(economics, aes(date, unemploy))\n\nb <- ggplot(seals, aes(x = long, y = lat))\n```\n:::\n\n\n- `a + geom_blank()` and `a + expand_limits()`: Ensure limits include values across all plots.\n\n- `b + geom_curve(aes(yend = lat + 1, xend = long + 1), curvature = 1)`: Draw a curved line from `(x, y)` to `(xend, yend)`.\n `aes()` arguments: `x`, `xend`, `y`, `yend`, `alpha`, `angle`, `color`, `curvature`, `linetype`, `size`.\n\n- `a + geom_path(lineend = \"butt\", linejoin = \"round\", linemitre = 1)`: Connect observations in the order they appear.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `group`, `linetype`, `size`.\n\n- `a + geom_polygon(aes(alpha = 50))`: Connect points into polygons.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `group`, `subgroup`, `linetype`, `size`.\n\n- `b + geom_rect(aes(xmin = long, ymin = lat, xmax = long + 1, ymax = lat + 1))`: Draw a rectangle by connecting four corners (`xmin`, `xmax`, `ymin`, `ymax`).\n `aes()` arguments: `xmax`, `xmin`, `ymax`, `ymin`, `alpha`, `color`, `fill`, `linetype`, `size`.\n\n- `a + geom_ribbon(aes(ymin = unemploy - 900, ymax = unemploy + 900)`: For each `x`, plot an interval from `ymin` to `ymax`.\n `aes()` arguments: `x`, `ymax`, `ymin`, `alpha`, `color`, `fill`, `group`, `linetype`, `size`.\n\n#### Line Segments\n\nCommon aesthetics: `x`, `y`, `alpha`, `color`, `linetype`, `size`.\n\n- `b + geom_abline(aes(intercept = 0, slope = 1))`: Draw a diagonal reference line with a given `slope` and `intercept`.\n\n- `b + geom_hline(aes(yintercept = lat))`: Draw a horizontal reference line with a given `yintercept`.\n\n- `b + geom_vline(aes(xintercept = long))`: Draw a vertical reference line with a given `xintercept`.\n\n- `b + geom_segment(aes(yend = lat + 1, xend = long + 1))`: Draw a straight line from `(x, y)` to `(xend, yend)`.\n\n- `b + geom_spoke(aes(angle = 1:1155, radius = 1))`: Draw line segments using polar coordinates (`angle` and `radius`).\n\n### One Variable - Continuous\n\n\n::: {.cell}\n\n```{.r .cell-code}\nc <- ggplot(mpg, aes(hwy))\nc2 <- ggplot(mpg)\n```\n:::\n\n\n- `c + geom_area(stat = \"bin\")`: Draw an area plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `linetype`, `size`.\n\n- `c + geom_density(kernel = \"gaussian\")`: Compute and draw kernel density estimates.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `group`, `linetype`, `size`, `weight`.\n\n- `c + geom_dotplot()`: Draw a dot plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`.\n\n- `c + geom_freqpoly()`: Draw a frequency polygon.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `group`, `linetype`, `size`.\n\n- `c + geom_histogram(binwidth = 5)`: Draw a histogram.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `linetype`, `size`, `weight`.\n\n- `c2 + geom_qq(aes(sample = hwy))`: Draw a quantile-quantile plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `linetype`, `size`, `weight`.\n\n### One Variable - Discrete\n\n\n::: {.cell}\n\n```{.r .cell-code}\nd <- ggplot(mpg, aes(fl))\n```\n:::\n\n\n- `d + geom_bar()`: Draw a bar chart. `aes()` arguments: `x`, `alpha`, `color`, `fill`, `linetype`, `size`, `weight`.\n\n### Two Variables - Both Continuous\n\n\n::: {.cell}\n\n```{.r .cell-code}\ne <- ggplot(mpg, aes(cty, hwy))\n```\n:::\n\n\n- `e + geom_label(aes(label = cty), nudge_x = 1, nudge_y = 1)`: Add text with a rectangle background.\n `aes()` arguments: - `x`, `y`, `label`, `alpha`, `angle`, `color`, `family`, `fontface`, `hjust`, `lineheight`, `size`, `vjust`.\n\n- `e + geom_point()`: Draw a scatter plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `shape`, `size`, `stroke`.\n\n- `e + geom_quantile()`: Fit and draw quantile regression for the plot data.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `group`, `linetype`, `size`, `weight`.\n\n- `e + geom_rug(sides = \"bl\")`: Draw a rug plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `linetype`, `size`.\n\n- `e + geom_smooth(method = lm)`: Plot smoothed conditional means.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `group`, `linetype`, `size`, `weight`.\n\n- `e + geom_text(aes(label = cty), nudge_x = 1, nudge_y = 1)`: Add text to a plot.\n `aes()` arguments: `x`, `y`, `label`, `alpha`, `angle`, `color`, `family`, `fontface`, `hjust`, `lineheight`, `size`, `vjust`.\n\n### Two Variables - One Discrete, One Continuous\n\n\n::: {.cell}\n\n```{.r .cell-code}\nf <- ggplot(mpg, aes(class, hwy))\n```\n:::\n\n\n- `f + geom_col()`: Draw a bar plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `group`, `linetype`, `size`.\n\n- `f + geom_boxplot()`: Draw a box plot.\n `aes()` arguments: `x`, `y`, `lower`, `middle`, `upper`, `ymax`, `ymin`, `alpha`, `color`, `fill`, `group`, `linetype`, `shape`, `size`, `weight`.\n\n- `f + geom_dotplot(binaxis =\"y\", stackdir = \"center\")`: Draw a dot plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `group`.\n\n- `f + geom_violin(scale = \"area\")`: Draw a violin plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `group`, `linetype`, `size`, `weight`.\n\n### Two Variables - Both Discrete\n\n\n::: {.cell}\n\n```{.r .cell-code}\ng <- ggplot(diamonds, aes(cut, color))\n```\n:::\n\n\n- `g + geom_count()`: Plot a count of points in an area to address over plotting.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `shape`, `size`, `stroke`.\n\n- `e + geom_jitter(height = 2, width = 2)`: Jitter points in a plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `shape`, `size`.\n\n### Two Variables - Continuous Bivariate Distribution\n\n\n::: {.cell}\n\n```{.r .cell-code}\nh <- ggplot(diamonds, aes(carat, price))\n```\n:::\n\n\n- `h + geom_bin2d(binwidth = c(0.25, 500))`: Draw a heatmap of 2D rectangular bin counts.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `linetype`, `size`, `weight`.\n\n- `h + geom_density_2d()`: Plot contours from 2D kernel density estimation.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `group`, `linetype`, `size`.\n\n- `h + geom_hex()`: Draw a heatmap of 2D hexagonal bin counts.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `size`.\n\n### Two Variables - Continuous Function\n\n\n::: {.cell}\n\n```{.r .cell-code}\ni <- ggplot(economics, aes(date, unemploy))\n```\n:::\n\n\n- `i + geom_area()`: Draw an area plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `linetype`, `size`.\n\n- `i + geom_line()`: Connect data points, ordered by the x axis variable.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `group`, `linetype`, `size`.\n\n- `i + geom_step(direction = \"hv\"`: Draw a stairstep plot. `aes()` arguments: `x`, `y`, `alpha`, `color`, `group`, `linetype`, `size`.\n\n### Two Variables - Visualizing Error\n\n\n::: {.cell}\n\n```{.r .cell-code}\ndf <- data.frame(grp = c(\"A\", \"B\"), fit = 4:5, se = 1:2)\nj <- ggplot(df, aes(grp, fit, ymin = fit - se, ymax = fit + se))\n```\n:::\n\n\n- `j + geom_crossbar(fatten = 2)`: Draw a crossbar.\n `aes()` arguments: `x`, `y`, `ymax`, `ymin`, `alpha`, `color`, `fill`, `group`, `linetype`, `size`.\n\n- `j + geom_errorbar()`: Draw an errorbar.\n Also `geom_errorbarh()`.\n `aes()` arguments: `x`, `ymax`, `ymin`, `alpha`, `color`, `group`, `linetype`, `size`, `width`.\n\n- `j + geom_linerange()`: Draw a line range.\n `aes()` arguments: `x`, `ymin`, `ymax`, `alpha`, `color`, `group`, `linetype`, `size`.\n\n- `j + geom_pointrange()`: Draw a point range.\n `aes()` arguments: `x`, `y`, `ymin`, `ymax`, `alpha`, `color`, `fill`, `group`, `linetype`, `shape`, `size`.\n\n### Two Variables - Maps\n\n\n::: {.cell}\n\n```{.r .cell-code}\nmurder_data <- data.frame(\n murder = USArrests$Murder, \n state = tolower(rownames(USArrests))\n)\nmap <- map_data(\"state\")\nk <- ggplot(murder_data, aes(fill = murder))\n```\n:::\n\n\n- `k + geom_map(aes(map_id = state), map = map) + expand_limits(x = map$long, y = map$lat)`: Draw polygons as a map. `aes()` arguments: `map_id`, `alpha`, `color`, `fill`, `linetype`, `size`.\n\n### Three Variables\n\n\n::: {.cell}\n\n```{.r .cell-code}\nseals$z <- with(seals, sqrt(delta_long^2 + delta_lat^2))\nl <- ggplot(seals, aes(long, lat))\n```\n:::\n\n\n- `l + geom_contour(aes(z = z))`: Draw 2D contour plot.\n `aes()` arguments: `x`, `y`, `z`, `alpha`, `color`, `group`, `linetype`, `size`, `weight`.\n\n- `l + geom_contour_filled(aes(fill = z))`: Draw 2D contour plot with the space between lines filled.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `group`, `linetype`, `size`, `subgroup`.\n\n- `l + geom_raster(aes(fill = z), hjust = 0.5, vjust = 0.5, interpolate = FALSE)`: Draw a raster plot.\n `aes()` arguments: `x`, `y`, `alpha`, `fill`.\n\n- `l + geom_tile(aes(fill = z))`: Draw a tile plot.\n `aes()` arguments: `x`, `y`, `alpha`, `color`, `fill`, `linetype`, `size`, `width`.\n\n\n\n## Stats\n\nAn alternative way to build a layer.\n\nA stat builds new variables to plot (e.g., count, prop).\n\nVisualize a stat by changing the default stat of a geom function, `geom_bar(stat = \"count\")`, or by using a stat function, `stat_count(geom = \"bar\")`, which calls a default geom to make a layer (equivalent to a geom function).\nUse `..name..` syntax to map stat variables to aesthetics.\n\n\n::: {.cell}\n\n```{.r .cell-code}\ni + stat_density_2d(aes(fill = ..level..), geom = \"polygon\")\n```\n:::\n\n\nIn this example, `\"polygon\"` is the geom to use, `stat_density_2d()` is the stat function, `aes()` contains the geom mappings, and `..level..` is the variable created by stat.\n\n- `c + stat_bin(binwidth = 1, boundary = 10)`: `x`, `y` \\| `..count..`, `..ncount..`, `..density..`, `..ndensity..`\n\n- `c + stat_count(width = 1)`: `x`, `y` \\| `..count..`, `..density..`\n\n- `c + stat_density(adjust = 1, kernel = \"gaussian\")`: `x`, `y` \\| `..count..`, `..density..`, `..scaled..`\n\n- `e + stat_bin_2d(bins = 30, drop = T)`: `x`, `y`, `fill` \\| `..count..`, `..density..`\n\n- `e + stat_bin_hex(bins =30)`: `x`, `y`, `fill` \\| `..count..`, `..density..`\n\n- `e + stat_density_2d(contour = TRUE, n = 100)`: `x`, `y`, `color`, `size` \\| `..level..`\n\n- `e + stat_ellipse(level = 0.95, segments = 51, type = \"t\")`\n\n- `l + stat_contour(aes(z = z))`: `x`, `y`, `z`, `order` \\| `..level..`\n\n- `l + stat_summary_hex(aes(z = z), bins = 30, fun = max)`: `x`, `y`, `z`, `fill` \\| `..value..`\n\n- `l + stat_summary_2d(aes(z = z), bins = 30, fun = mean)`: `x`, `y`, `z`, `fill` \\| `..value..`\n\n- `f + stat_boxplot(coef = 1.5)`: `x`, `y` \\| `..lower..`, `..middle..`, `..upper..`, `..width..`, `..ymin..`, `..ymax..`\n\n- `f + stat_ydensity(kernel = \"gaussian\", scale = \"area\")`: `x`, `y` \\| `..density..`, `..scaled..`, `..count..`, `..n..`, `..violinwidth..`, `..width..`\n\n- `e + stat_ecdf(n = 40)`: `x`, `y` \\| `..x..`, `..y..`\n\n- `e + stat_quantile(quantiles = c(0.1, 0.9), formula = y ~ log(x), method = \"rq\")`: `x`, `y` \\| `..quantile..`\n\n- `e + stat_smooth(method = \"lm\", formula = y ~ x, se = T, level = 0.95)`: `x`, `y` \\| `..se..`, `..x..`, `..y..`, `..ymin..`, `..ymax..`\n\n- `ggplot() + xlim(-5, 5) + stat_function(fun = dnorm, n = 20, geom = \"point\")`: `x` \\| `..x..`, `..y..`\n\n- `ggplot() + stat_qq(aes(sample = 1:100))`: `x`, `y`, `sample` \\| `..sample..`, `..theoretical..`\n\n- `e + stat_sum()`: `x`, `y`, `size` \\| `..n..`, `..prop..`\n\n- `e + stat_summary(fun.data = \"mean_cl_boot\")`\n\n- `h + stat_summary_bin(fun = \"mean\", geom = \"bar\")`\n\n- `e + stat_identity()`\n\n- `e + stat_unique()`\n\n## Scales\n\nOverride defaults with **scales** package.\n\n**Scales** map data values to the visual values of an aesthetic.\nTo change a mapping, add a new scale.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nn <- d + geom_bar(aes(fill = fl))\n\nn + scale_fill_manual(\n value = c(),\n limits = c(), \n breaks = c(),\n name = \"fuel\", \n labels = c(\"D\", \"E\", \"P\", \"R\")\n)\n```\n:::\n\n\nIn this example, `scale_` specifies a scale function, `fill` is the aesthetic to adjust, and `manual` is the prepackaged scale to use.\n\n`values` contains scale-specific arguments, `limits` specifies the range of values to include in mappings, `breaks` specifies the breaks to use in legend/axis, and `name` and `labels` specify the title and labels to use in the legend/axis.\n\n### General Purpose Scales\n\nUse with most aesthetics.\n\n- `scale_*_continuous()`: Map continuous values to visual ones.\n\n- `scale_*_discrete()`: Map discrete values to visual ones.\n\n- `scale_*_binned()`: Map continuous values to discrete bins.\n\n- `scale_*_identity()`: Use data values as visual ones.\n\n- `scale_*_manual(values = c())`: Map discrete values to manually chosen visual ones.\n\n- `scale_*_date(date_labels = \"%m/%d\", date_breaks = \"2 weeks\")`: Treat data values as dates.\n\n- `scale_*_datetime()`: Treat data values as date times.\n Same as `scale_*_date()`.\n See `?strptime` for label formats.\n\n### X & Y Location Scales\n\nUse with x or y aesthetics (x shown here).\n\n- `scale_x_log10()`: Plot `x` on log10 scale.\n\n- `scale_x_reverse()`: Reverse the direction of the x axis.\n\n- `scale_x_sqrt()`: Plot `x` on square root scale.\n\n### Color and Fill Scales (Discrete)\n\n- `n + scale_fill_brewer(palette = \"Blues\")`: Use color scales from ColorBrewer.\n For palette choices `RColorBrewer::display.brewer.all()`.\n\n- `n + scale_fill_grey(start = 0.2, end = 0.8, na.value = \"red\")`: Use a grey gradient color scale.\n\n### Color and Fill Scales (Continuous)\n\n\n::: {.cell}\n\n```{.r .cell-code}\no <- c + geom_dotplot(aes(fill = ..x..))\n```\n:::\n\n\n- `o + scale_fill_distiller(palette = \"Blues\")`: Interpolate a palette into a continuous scale.\n\n- `o + scale_fill_gradient(low = \"red\", high = \"yellow\")`: Create a two color gradient.\n\n- `o + scale_fill_gradient2(low = \"red\", high = \"blue\", mid = \"white\", midpoint = 25)`: Create a diverging color gradient.\n\n- `o + scale_fill_gradientn(colors = topo.colors(6))`: Create a n-color gradient.\n Also `rainbow()`, `heat.colors()`, `terrain.colors()`, `cm.colors()`, `RColorBrewer::brewer.pal()`.\n\n### Shape and Size Scales\n\n\n::: {.cell}\n\n```{.r .cell-code}\np <- e + geom_point(aes(shape = fl, size = cyl))\n```\n:::\n\n\n- `p + scale_shape() + scale_size()`: Map discrete values to shape and size aesthetics.\n\n- `p + scale_shape_manual(values = c(3:7))`: Map discrete values to specified shape values.\n\n- `p + scale_radius(range = c(1,6))`: Map values to a shape's radius.\n\n- `p + scale_size_area(max_size = 6)`: Like `scale_size()` but maps zero values to zero size.\n\nShapes used here are the same as the ones listed in the Aes section.\n\n## Coordinate Systems\n\n\n::: {.cell}\n\n```{.r .cell-code}\nu <- d + geom_bar()\n```\n:::\n\n\n- `u + coord_cartesian(xlim = c(0, 5))`: `xlim`, `ylim`.\n The default Cartesian coordinate system.\n\n- `u + coord_fixed(ratio = 1/2)`: `ratio`, `xlim`, `ylim`.\n Cartesian coordinates with fixed aspect ration between x and y units.\n\n- `ggplot(mpg, aes(y = fl)) + geom_bar()`: Flip Cartesian coordinates by switching x and y aesthetic mappings.\n\n- `u + coord_polar(theta = \"x\", direction = 1)`: `theta`, `start`, `direction`.\n Polar coordinates.\n\n- `u + coord_trans(y = \"sqrt\")`: `x`, `y`, `xlim`, `ylim`.\n Transformed Cartesian coordinates.\n Set `xtrans` and `ytrans` to the name of a window function.\n\n- `π + coord_quickmap(); π + coord_map(projection = \"ortho\", orientation = c(41, -74, 0))`: `projection`, `xlim`, `ylim`.\n Map projections from the **mapproj** packages (`mercator` (default), `azequalarea`, `lagrange`, etc.).\n\n## Position Adjustments\n\nPosition adjustments determine how to arrange geoms that would otherwise occupy the same space.\n\n\n::: {.cell}\n\n```{.r .cell-code}\ns <- ggplot(mpg, aes(fl, fill = drv))\n```\n:::\n\n\n- `s + geom_bar(position = \"dodge\")`: Arrange elements side by side.\n\n- `s + geom_bar(position = \"fill\")`: Stack elements on top of one another, normalize height.\n\n- `e + geom_point(position = \"jitter\")`: Add random noise to X and Y position of each element to avoid over plotting.\n\n- `e + geom_label(position = \"nudge\")`: Nudge labels away from points.\n\n- `s + geom_bar(position = \"stack\")`: Stack elements on top of one another.\n\nEach position adjustment can be recast as a function with manual `width` and `height` arguments:\n\n\n::: {.cell}\n\n```{.r .cell-code}\ns + geom_bar(position = position_dodge(width = 1))\n```\n:::\n\n\n## Themes\n\n- `u + theme_bw()`: White background with grid lines.\n\n- `u + theme_gray()`: Grey background with white grid lines (default theme).\n\n- `u + theme_dark()`: Dark grey background and grid lines for contrast.\n\n- `u + theme_classic()`: No grid lines.\n\n- `u + theme_light()`: Light grey axes and grid lines.\n\n- `u + theme_linedraw()`: Uses only black lines.\n\n- `u + theme_minimal()`: Minimal theme.\n\n- `u + theme_void()`: Empty theme.\n\n- `u + theme()`: Customize aspects of the theme such as axis, legend, panel, and facet properties.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n r + ggtitle(\"Title\") + theme(plot.title.postion = \"plot\")\n \n r + theme(panel.background = element_rect(fill = \"blue\"))\n ```\n :::\n\n\n## Faceting\n\nFacets divide a plot into subplots based on the values of one or more discrete variables.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nt <- ggplot(mpg, aes(cty, hwy)) + geom_point()\n```\n:::\n\n\n- `t + facet_grid(cols = vars(fl))`: Facet into a column based on fl.\n\n- `t + facet_grid(rows = vars(year))`: Facet into rows based on year.\n\n- `t + facet_grid(rows = vars(year), cols = vars(fl))`: Facet into both rows and columns.\n\n- `t_facet_wrap(vars(fl))`: Wrap facets into a rectangular layout.\n\n- `t + facet_grid(rows = vars(drv), cols = vars(fl), scales = \"free\")`: Set **scales** to let axis limits vary across facets.\n Also `\"free_x\"` for x axis limits adjust to individual facets and `\"free_y\"` for y axis limits adjust to individual facets.\n\nSet **labeller** to adjust facet label:\n\n- `t + facet_grid(cols = vars(fl), labeller = label_both)`: Labels each facet as \"fl: c\", \"fl: d\", etc.\n\n- `t + facet_grid(rows = vars(fl), labeller = label_bquote(alpha ^ .(fl)))`: Labels each facet as \"𝛼^c^\", \"𝛼^d^\", etc.\n\n## Labels and Legends\n\nUse `labs()` to label elements of your plot.\n\n``` \nt + labs(x = \"New x axis label\", \n y = \"New y axis label\",\n title =\"Add a title above the plot\",\n subtitle = \"Add a subtitle below title\",\n caption = \"Add a caption below plot\",\n alt = \"Add alt text to the plot\",\n = \"New legend title\")\n```\n\n- `t + annotate(geom = \"text\", x = 8, y = 9, label = \"A\")`: Places a geom with manually selected aesthetics.\n\n- `p + guides(x = guide_axis(n.dodge = 2))`: Avoid crowded or overlapping labels with `guide_axis(n.dodge or angle)`.\n\n- `n + guides(fill = \"none\")`: Set legend type for each aesthetic: `colorbar`, `legend`, or `none` (no legend).\n\n- `n + theme(legend.position = \"bottom\")`: Place legend at \"bottom\", \"top\", \"left\", or \"right\".\n\n- `n + scale_fill_discrete(name = \"Title\", labels = c(\"A\", \"B\", \"C\", \"D\", \"E\"))`: Set legend title and labels with a scale function.\n\n## Zooming\n\n- `t + coord_cartesian(xlim = c(0, 100), ylim = c(10,20))`: Zoom without clipping (preferred).\n\n- `t + xlim(0, 100) + ylim(10, 20)` or `t + scale_x_continuous(limits = c(0, 100)) + scale_y_continuous(limits = c(0, 100))`: Zoom with clipping (removes unseen data points).\n", "supporting": [], "filters": [ "rmarkdown/pagebreak.lua" diff --git a/_freeze/html/factors/execute-results/html.json b/_freeze/html/factors/execute-results/html.json index c1040e33..7ad80ee5 100644 --- a/_freeze/html/factors/execute-results/html.json +++ b/_freeze/html/factors/execute-results/html.json @@ -1,7 +1,7 @@ { - "hash": "4a2e8abe80fb98b01cb607700ce24a02", + "hash": "49601350c49c834abf551b0a9230b77d", "result": { - "markdown": "---\ntitle: \"Factors with forcats :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: false\n---\n\n::: {.cell .column-margin}\n\"\"\n

\n

Download PDF

\n\n
\n

Translations (PDF)

\n* Japanese\n* Spanish\n:::\n\n\nThe **forcats** package provides tools for working with factors, which are R's data structure for categorical data.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(forcats)\n```\n:::\n\n\n\n\n## Factors\n\nR represents categorical data with factors.\nA **factor** is an integer vector with a **levels** attribute that stores a set of mappings between integers and categorical values.\nWhen you view a factor, R displays not the integers but the levels associated with them.\n\nFor example, R will display `c(\"a\", \"c\", \"b\", \"a\")` with levels `c(\"a\", \"b\", \"c\")` but will store `c(1, 3, 2, 1)` where 1 = a, 2 = b, and 3 = c.\n\nR will display:\n\n\n::: {.cell}\n::: {.cell-output .cell-output-stdout}\n```\n[1] a c b a\nLevels: a b c\n```\n:::\n:::\n\n\nR will store:\n\n\n::: {.cell}\n::: {.cell-output .cell-output-stdout}\n```\n[1] 1 3 2 1\nattr(,\"levels\")\n[1] \"a\" \"b\" \"c\"\n```\n:::\n:::\n\n\nCreate a factor with `factor()`:\n\n- `factor(x = character(), levels, labels = levels, exclude = NA, ordered = is.ordered(x), nmax = NA)`: Convert a vector to a factor.\n Also `as_factor()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n f <- factor(c(\"a\", \"c\", \"b\", \"a\"), levels = c(\"a\", \"b\", \"c\"))\n ```\n :::\n\n\nReturn its levels with `levels()`:\n\n- `levels(x)`: Return/set the levels of a factor.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n levels(f)\n levels(f) <- c(\"x\", \"y\", \"z\")\n ```\n :::\n\n\nUse `unclass()` to see its structure.\n\n## Inspect Factors\n\n- `fct_count(f, sort = FALSE, prop = FALSE)`: Count the number of values with each level.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_count(f)\n ```\n :::\n\n\n- `fct_match(f, lvls)`: Check for `lvls` in `f`.\n\n\n \n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_match(f, \"a\")\n ```\n :::\n\n\n- `fct_unique(f)`: Return the unique values, removing duplicates.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_unique(f)\n ```\n :::\n\n\n## Combine Factors\n\n- `fct_c(...)`: Combine factors with different levels.\n Also `fct_cross()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n f1 <- factor(c(\"a\", \"c\"))\n f2 <- factor(c(\"b\", \"a\"))\n fct_c(f1, f2)\n ```\n :::\n\n\n- `fct_unify(fs, levels = lvls_union(fs))`: Standardize levels across a list of factors.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_unify(list(f2, f1))\n ```\n :::\n\n\n## Change the order of levels\n\n- `fct_relevel(.f, ..., after = 0L)`: Manually reorder factor levels.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_relevel(f, c(\"b\", \"c\", \"a\"))\n ```\n :::\n\n\n- `fct_infreq(f, ordered = NA)`: Reorder levels by the frequency in which they appear in the data (highest frequency first).\n Also `fct_inseq()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n f3 <- factor(c(\"c\", \"c\", \"a\"))\n fct_infreq(f3)\n ```\n :::\n\n\n- `fct_inorder(f, ordered = NA)`: Reorder levels by order in which they appear in the data.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_inorder(f2)\n ```\n :::\n\n\n- `fct_rev(f)`: Reverse level order.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n f4 <- factor(c(\"a\",\"b\",\"c\"))\n fct_rev(f4)\n ```\n :::\n\n\n- `fct_shift(f)`: Shift levels to left or right, wrapping around end.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_shift(f4)\n ```\n :::\n\n\n- `fct_shuffle(f, n = 1L)`: Randomly permute order of factor levels.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_shuffle(f4)\n ```\n :::\n\n\n- `fct_reorder(.f, .x, .fun = median, ..., .desc = FALSE)`: Reorder levels by their relationship with another variable.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n boxplot(PlantGrowth, weight ~ fct_reorder(group, weight))\n ```\n :::\n\n\n- `fct_reorder2(.f, .x, .y, .fun = last2, ..., .desc = TRUE)`: Reorder levels by their final values when plotted with two other variables.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n ggplot(\n diamonds,\n aes(carat, price, color = fct_reorder2(color, carat, price))\n ) + \n geom_smooth()\n ```\n :::\n\n\n## Change the value of levels\n\n- `fct_recode(.f, ...)`: Manually change levels.\n Also `fct_relabel()` which obeys `purrr::map` syntax to apply a function or expression to each level.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_recode(f, v = \"a\", x = \"b\", z = \"c\")\n fct_relabel(f, ~ paste0(\"x\", .x))\n ```\n :::\n\n\n- `fct_anon(f, prefix = \"\")`: Anonymize levels with random integers.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_anon(f)\n ```\n :::\n\n\n- `fct_collapse(.f, …, other_level = NULL)`: Collapse levels into manually defined groups.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_collapse(f, x = c(\"a\", \"b\"))\n ```\n :::\n\n\n- `fct_lump_min(f, min, w = NULL, other_level = \"Other\")`: Lumps together factors that appear fewer than `min` times.\n Also `fct_lump_n()`, `fct_lump_prop()`, and `fct_lump_lowfreq()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_lump_min(f, min = 2)\n ```\n :::\n\n\n- `fct_other(f, keep, drop, other_level = \"Other\")`: Replace levels with \"other.\"\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_other(f, keep = c(\"a\", \"b\"))\n ```\n :::\n\n\n## Add or drop levels\n\n- `fct_drop(f, only)`: Drop unused levels.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n f5 <- factor(c(\"a\",\"b\"),c(\"a\",\"b\",\"x\"))\n f6 <- fct_drop(f5)\n ```\n :::\n\n\n- `fct_expand(f, ...)`: Add levels to a factor.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_expand(f6, \"x\")\n ```\n :::\n\n\n- `fct_na_value_to_level(f, level = \"(Missing)\")`: Assigns a level to NAs to ensure they appear in plots, etc.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n f <- factor(c(\"a\", \"b\", NA))\n fct_na_value_to_level(f, level = \"(Missing)\")\n ```\n :::\n\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [forcats.tidyverse.org](https://forcats.tidyverse.org).\n\nUpdated: 2023-05.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"forcats\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.0.0'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", + "markdown": "---\ntitle: \"Factors with forcats :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: false\n---\n\n::: {.cell .column-margin}\n\"Hex\n

\n

Download PDF

\n\"\"/\n
\n

Translations (PDF)

\n* Japanese\n* Spanish\n:::\n\n\nThe **forcats** package provides tools for working with factors, which are R's data structure for categorical data.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(forcats)\n```\n:::\n\n\n\n\n## Factors\n\nR represents categorical data with factors.\nA **factor** is an integer vector with a **levels** attribute that stores a set of mappings between integers and categorical values.\nWhen you view a factor, R displays not the integers but the levels associated with them.\n\nFor example, R will display `c(\"a\", \"c\", \"b\", \"a\")` with levels `c(\"a\", \"b\", \"c\")` but will store `c(1, 3, 2, 1)` where 1 = a, 2 = b, and 3 = c.\n\nR will display:\n\n\n::: {.cell}\n::: {.cell-output .cell-output-stdout}\n```\n[1] a c b a\nLevels: a b c\n```\n:::\n:::\n\n\nR will store:\n\n\n::: {.cell}\n::: {.cell-output .cell-output-stdout}\n```\n[1] 1 3 2 1\nattr(,\"levels\")\n[1] \"a\" \"b\" \"c\"\n```\n:::\n:::\n\n\nCreate a factor with `factor()`:\n\n- `factor(x = character(), levels, labels = levels, exclude = NA, ordered = is.ordered(x), nmax = NA)`: Convert a vector to a factor.\n Also `as_factor()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n f <- factor(c(\"a\", \"c\", \"b\", \"a\"), levels = c(\"a\", \"b\", \"c\"))\n ```\n :::\n\n\nReturn its levels with `levels()`:\n\n- `levels(x)`: Return/set the levels of a factor.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n levels(f)\n levels(f) <- c(\"x\", \"y\", \"z\")\n ```\n :::\n\n\nUse `unclass()` to see its structure.\n\n## Inspect Factors\n\n- `fct_count(f, sort = FALSE, prop = FALSE)`: Count the number of values with each level.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_count(f)\n ```\n :::\n\n\n- `fct_match(f, lvls)`: Check for `lvls` in `f`.\n\n\n \n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_match(f, \"a\")\n ```\n :::\n\n\n- `fct_unique(f)`: Return the unique values, removing duplicates.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_unique(f)\n ```\n :::\n\n\n## Combine Factors\n\n- `fct_c(...)`: Combine factors with different levels.\n Also `fct_cross()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n f1 <- factor(c(\"a\", \"c\"))\n f2 <- factor(c(\"b\", \"a\"))\n fct_c(f1, f2)\n ```\n :::\n\n\n- `fct_unify(fs, levels = lvls_union(fs))`: Standardize levels across a list of factors.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_unify(list(f2, f1))\n ```\n :::\n\n\n## Change the order of levels\n\n- `fct_relevel(.f, ..., after = 0L)`: Manually reorder factor levels.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_relevel(f, c(\"b\", \"c\", \"a\"))\n ```\n :::\n\n\n- `fct_infreq(f, ordered = NA)`: Reorder levels by the frequency in which they appear in the data (highest frequency first).\n Also `fct_inseq()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n f3 <- factor(c(\"c\", \"c\", \"a\"))\n fct_infreq(f3)\n ```\n :::\n\n\n- `fct_inorder(f, ordered = NA)`: Reorder levels by order in which they appear in the data.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_inorder(f2)\n ```\n :::\n\n\n- `fct_rev(f)`: Reverse level order.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n f4 <- factor(c(\"a\",\"b\",\"c\"))\n fct_rev(f4)\n ```\n :::\n\n\n- `fct_shift(f)`: Shift levels to left or right, wrapping around end.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_shift(f4)\n ```\n :::\n\n\n- `fct_shuffle(f, n = 1L)`: Randomly permute order of factor levels.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_shuffle(f4)\n ```\n :::\n\n\n- `fct_reorder(.f, .x, .fun = median, ..., .desc = FALSE)`: Reorder levels by their relationship with another variable.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n boxplot(PlantGrowth, weight ~ fct_reorder(group, weight))\n ```\n :::\n\n\n- `fct_reorder2(.f, .x, .y, .fun = last2, ..., .desc = TRUE)`: Reorder levels by their final values when plotted with two other variables.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n ggplot(\n diamonds,\n aes(carat, price, color = fct_reorder2(color, carat, price))\n ) + \n geom_smooth()\n ```\n :::\n\n\n## Change the value of levels\n\n- `fct_recode(.f, ...)`: Manually change levels.\n Also `fct_relabel()` which obeys `purrr::map` syntax to apply a function or expression to each level.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_recode(f, v = \"a\", x = \"b\", z = \"c\")\n fct_relabel(f, ~ paste0(\"x\", .x))\n ```\n :::\n\n\n- `fct_anon(f, prefix = \"\")`: Anonymize levels with random integers.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_anon(f)\n ```\n :::\n\n\n- `fct_collapse(.f, …, other_level = NULL)`: Collapse levels into manually defined groups.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_collapse(f, x = c(\"a\", \"b\"))\n ```\n :::\n\n\n- `fct_lump_min(f, min, w = NULL, other_level = \"Other\")`: Lumps together factors that appear fewer than `min` times.\n Also `fct_lump_n()`, `fct_lump_prop()`, and `fct_lump_lowfreq()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_lump_min(f, min = 2)\n ```\n :::\n\n\n- `fct_other(f, keep, drop, other_level = \"Other\")`: Replace levels with \"other.\"\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_other(f, keep = c(\"a\", \"b\"))\n ```\n :::\n\n\n## Add or drop levels\n\n- `fct_drop(f, only)`: Drop unused levels.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n f5 <- factor(c(\"a\",\"b\"),c(\"a\",\"b\",\"x\"))\n f6 <- fct_drop(f5)\n ```\n :::\n\n\n- `fct_expand(f, ...)`: Add levels to a factor.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fct_expand(f6, \"x\")\n ```\n :::\n\n\n- `fct_na_value_to_level(f, level = \"(Missing)\")`: Assigns a level to NAs to ensure they appear in plots, etc.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n f <- factor(c(\"a\", \"b\", NA))\n fct_na_value_to_level(f, level = \"(Missing)\")\n ```\n :::\n\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [forcats.tidyverse.org](https://forcats.tidyverse.org).\n\nUpdated: 2023-06.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"forcats\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.0.0'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", "supporting": [ "factors_files" ], diff --git a/_freeze/html/keras/execute-results/html.json b/_freeze/html/keras/execute-results/html.json index 944d19ee..f97ad4a1 100644 --- a/_freeze/html/keras/execute-results/html.json +++ b/_freeze/html/keras/execute-results/html.json @@ -1,7 +1,7 @@ { - "hash": "cba97761b965be4eb82ccbc0bcc88430", + "hash": "ed7ca780095848bb236e0eb3fef067cd", "result": { - "markdown": "---\ntitle: \"Deep Learning with Keras :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: false\n output: true\n warning: false\n---\n\n::: {.cell .column-margin}\n\"\"\n

\n

Download PDF

\n\n
\n

Translations (PDF)

\n* Chinese\n* Japanese\n* Spanish\n:::\n\n\n## Intro\n\n**Keras** is a high-level neural networks API developed with a focus on enabling fast experimentation.\nIt supports multiple back-ends, including TensorFlow, CNTK and Theano.\n\nTensorFlow is a lower level mathematical library for building deep neural network architectures.\nThe **keras** R package makes it easy to use Keras and TensorFlow in R.\n\n1. **Define**: Model, Sequential model, Multi-GPU model\n2. **Compile**: Optimizer, Loss, Metrics\n3. **Fit**: Batch size, Epochs, Validation split\n4. **Evaluate**: Evaluate, Plot\n5. **Predict**: Classes, Probability\n\nRead more at:\\\n\\\n\n\n### Installation\n\nThe keras R package uses the Python keras library.\nYou can install all the prerequisites directly from R: .\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(keras)\ninstall_keras()\n```\n:::\n\n\nSee `?install_keras` for GPU instructions.\n\nThis installs the required libraries in an Anaconda environment or virtual environment `r-tensorflow`.\n\n### Training an Image Recognizer on MNIST Data\n\nThe \"Hello, World!\" of deep learning\n\n\n::: {.cell}\n\n```{.r .cell-code}\n# input layer: use MNIST images\nmnist <- dataset_mnist()\nx_train <- mnist$train$x\ny_train <- mnist$train$y \nx_test <- mnist$test$x\ny_test <- mnist$test$y\n\n# reshape and rescale\nx_train <- array_reshape(x_train, c(nrow(x_train), 784)) \nx_test <- array_reshape(x_test, c(nrow(x_test), 784)) \nx_train <- x_train / 255\nx_test <- x_test / 255\n\ny_train <- to_categorical(y_train, 10) \ny_test <- to_categorical(y_test, 10)\n\n# defining the model and layers\nmodel <- keras_model_sequential() \nmodel %>%\n layer_dense(units = 256, activation = 'relu', input_shape = c(784)) %>%\n layer_dropout(rate = 0.4) %>% \n layer_dense(units = 128, activation = 'relu') %>% \n layer_dense(units = 10, activation = 'softmax')\n \n# compile (define loss and optimizer)\nmodel %>%\n compile(\n loss = 'categorical_crossentropy', \n optimizer = optimizer_rmsprop(), \n metrics = c('accuracy')\n)\n\n# train (fit)\nmodel %>% fit(\n x_train, y_train,\n epochs = 30, batch_size = 128, \n validation_split = 0.2\n)\n\nmodel %>% evaluate(x_test, y_test) \nmodel %>% predict_classes(x_test)\n```\n:::\n\n\n## Working with keras models\n\n### Define a Model\n\n- `keras_model()`: Keras Model.\n\n- `keras_model_sequential()`: Keras Model composed of a linear stack of layers.\n\n- `multi_gpu_model()`: Replicates a model on different GPUs.\n\n### Compile a Model\n\n- `compile(object, optimizer, loss, metrics = NULL)`: Configure a Keras model for training.\n\n### Fit a Model\n\n- `fit(object, x = NULL, y = NULL, batch_size = NULL, epochs = 10, verbose = 1, callbacks = NULL, ...)`: Train a Keras model for a fixed number of epochs (iterations).\n\n- `fit_generator()`: Fits the model on data yielded batch-by-batch by a generator.\n\n- `train_on_batch()`; `test_on_batch()`: Single gradient update or model evaluation over one batch of samples.\n\n### Evaluate a Model\n\n- `evaluate(object, x = NULL, y = NULL, batch_size = NULL)`: Evaluate a Keras model.\n\n- `evaluate_generator()`: Evaluates the model on a data generator.\n\n### Predict\n\n- `predict()`: Generate predictions from a Keras model.\n\n- `predict_proba()`; `predict_classes()`: Generates probability or class probability predictions for the input samples.\n\n- `predict_on_batch()`: Returns predictions for a single batch of samples.\n\n- `predict_generator()`: Generates predictions for the input samples from a data generator.\n\n### Other Model Operations\n\n- `summary()`: Print a summary of a Keras model.\n\n- `export_savedmodel()`: Export a saved model.\n\n- `get_layer()`: Retrieves a layer based on either its name (unique) or index.\n\n- `pop_layer()`: Remove the last layer in a model.\n\n- `save_model_hdf5()`; `load_model_hdf5()`: Save/Load models using HDF5 files.\n\n- `serialize_model()`; `unserialize_model()`: Serialize a model to an R object.\n\n- `clone_model()`: Clone a model instance.\n\n- `freeze_weights()`; `unfreeze_weights()`\n\n### Core Layers\n\n- `layer_input()`: Input layer.\n\n- `layer_dense()`: Add a densely-connected NN layer to an output.\n\n- `layer_activation()`: Apply an activation function to an output.\n\n- `layer_dropout()`: Applies Dropout to the input.\n\n- `layer_reshape()`: Reshapes an output to a certain shape.\n\n- `layer_permute()`: Permute the dimensions of an input according to a given pattern.\n\n- `layer_repeat_vector()`: Repeats the input n times.\n\n- `layer_lambda(object, f)`: Wraps arbitrary expression as a layer.\n\n- `layer_activity_regularization()`: Layer that applies an update to the cost function based input activity.\n\n- `layer_masking()`: Masks a sequence by using a mask value to skip timesteps.\n\n- `layer_flatten()`: Flattens an input.\n\n\n\n## More layers\n\n### Convolutional Layers\n\n- `layer_conv_1d()`: 1D, e.g. temporal convolution.\n\n- `layer_conv_2d_transpose()`: Transposed 2D (deconvolution).\n\n- `layer_conv_2d()` : 2D, e.g. spatial convolution over images.\n\n- `layer_conv_3d_transpose()`: Transposed 3D (deconvolution).\n\n- `layer_conv_3d()`: 3D, e.g. spatial convolution over volumes.\n\n- `layer_conv_lstm_2d()`: Convolutional LSTM.\n\n- `layer_separable_conv_2d()`: Depthwise separable 2D.\n\n- `layer_upsampling_1d()`; `layer_upsampling_2d()`; `layer_upsampling_3d()`: Upsampling layer.\n\n- `layer_zero_padding_1d()`; `layer_zero_padding_2d()`; `layer_zero_padding_3d()`: Zero-padding layer.\n\n- `layer_cropping_1d()`; `layer_cropping_2d()`; `layer_cropping_3d()`: Cropping layer.\n\n### Pooling Layers\n\n- `layer_max_pooling_1d()`; `layer_max_pooling_2d()`; `layer_max_pooling_3d()`: Maximum pooling for 1D to 3D.\n\n- `layer_average_pooling_1d()`; `layer_average_pooling_2d()`; `layer_average_pooling_3d()`: Average pooling for 1D to 3D.\n\n- `layer_global_max_pooling_1d()`; `layer_global_max_pooling_2d()`; `layer_global_max_pooling_3d()`: Global maximum pooling.\n\n- `layer_global_average_pooling_1d()`; `layer_global_average_pooling_2d()`; `layer_global_average_pooling_3d()`: Global average pooling.\n\n### Activation Layers\n\n- `layer_activation(object, activation)`: Apply an activation function to an output.\n\n- `layer_activation_leaky_relu()`: Leaky version of a rectified linear unit.\n\n- `layer_activation_parametric_relu()`: Parametric rectified linear unit.\n\n- `layer_activation_thresholded_relu()`: Thresholded rectified linear unit.\n\n- `layer_activation_elu()`: Exponential linear unit.\n\n### Dropout Layers\n\n- `layer_dropout()`: Applies dropout to the input.\n\n- `layer_spatial_dropout_1d()`; `layer_spatial_dropout_2d()`; `layer_spatial_dropout_3d()`: Spatial 1D to 3D version of dropout\n\n### Recurrent Layers\n\n- `layer_simple_rnn()`: Fully-connected RNN where the output is to be fed back to input.\n\n- `layer_gru()`: Gated recurrent unit - Cho et al.\n\n- `layer_cudnn_gru()`: Fast GRU implementation backed by CuDNN.\n\n- `layer_lstm()`: Long-Short Term Memory unit - Hochreiter 1997.\n\n- `layer_cudnn_lstm()`: Fast LSTM implementation backed by CuDNN.\n\n### Locally Connected Layers\n\n- `layer_locally_connected_1d()`; `layer_locally_connected_2d()`: Similar to convolution, but weights are not shared, i.e. different filters for each patch.\n\n## Preprocessing\n\n### Sequence Preprocessing\n\n- `pad_sequences()`: Pads each sequence to the same length (length of the longest sequence).\n\n- `skipgrams()`: Generates skipgram word pairs.\n\n- `make_sampling_table()`: Generates word rank-based probabilistic sampling table.\n\n### Text Preprocessing\n\n- `text_tokenizer()`: Text tokenization utility.\n\n- `fit_text_tokenizer()`: Update tokenizer internal vocabulary.\n\n- `save_text_tokenizer()`; `load_text_tokenizer()`: Save a text tokenizer to an external file.\n\n- `texts_to_sequences()`; `texts_to_sequences_generator()`: Transforms each text in texts to sequence of integers.\n\n- `texts_to_matrix()`; `sequences_to_matrix()`: Convert a list of sequences into a matrix.\n\n- `text_one_hot()`: One-hot encode text to word indices.\n\n- `text_hashing_trick()`: Converts a text to a sequence of indexes in a fixed-size hashing space.\n\n- `text_to_word_sequence()`: Convert text to a sequence of words (or tokens).\n\n### Image Proprocessing\n\n- `image_load()`: Loads an image into PIL format.\n\n- `flow_images_from_data()`; `flow_images_from_directory()`: Generates batches of augmented/normalized data from images and labels, or a directory.\n\n- `image_data_generator()`: Generate minibatches of image data with real-time data augmentation.\n\n- `fit_image_data_generator()`: Fit image data generator internal statistics to some sample data.\n\n- `generator_next()`: Retrieve the next item.\n\n- `image_to_array()`; `image_array_resize()`; `image_array_save()`: 3D array representation.\n\n## Pre-trained models\n\nKeras applications are deep learning models that are made available alongside pre-trained weights.\nThese models can be used for prediction, feature extraction, and fine-tuning.\n\n- `application_xception()`; `xception_preprocess_input()`: Xception v1 model.\n\n- `application_inception_v3()`; `inception_v3_preprocess_input()`: Inception v3 model, with weights pre-trained on ImageNet.\n\n- `application_inception_resnet_v2()`; `inception_resnet_v2_preprocess_input()`: Inception-ResNet v2 model, with weights trained on ImageNet.\n\n- `application_vgg16()`; `application_vgg19()`: VGG16 and VGG19 models.\n\n- `application_resnet50()`: ResNet50 model.\n\n- `application_mobilenet()`; `mobilenet_preprocess_input()`; `mobilenet_decode_predictions()`; `mobilenet_load_model_hdf5()`: MobileNet model architecture.\n\nImageNet is a large database of images with labels, extensively used for deep learning.\n\n- `imagenet_preprocess_input()`; `imagenet_decode_predictions()`: Preprocesses a tensor encoding a batch of images for ImageNet, and decodes predictions.\n\n## Callbacks\n\nA callback is a set of functions to be applied at given stages of the training procedure.\nYou can use callbacks to get a view on internal states and statistics of the model during training.\n\n- `allback_early_stopping()`: Stop training when a monitored quantity has stopped improving.\n\n- `callback_learning_rate_scheduler()`: Learning rate scheduler.\n\n- `callback_tensorboard()`: TensorBoard basic visualizations.\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [tensorflow.rstudio.com](https://tensorflow.rstudio.com/).\n\nUpdated: 2023-05.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"keras\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '2.11.1'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", + "markdown": "---\ntitle: \"Deep Learning with Keras :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: false\n output: true\n warning: false\n---\n\n::: {.cell .column-margin}\n\"Hex\n

\n

Download PDF

\n\"\"/\n
\n

Translations (PDF)

\n* Chinese\n* Japanese\n* Spanish\n:::\n\n\n## Intro\n\n**Keras** is a high-level neural networks API developed with a focus on enabling fast experimentation.\nIt supports multiple back-ends, including TensorFlow, CNTK and Theano.\n\nTensorFlow is a lower level mathematical library for building deep neural network architectures.\nThe **keras** R package makes it easy to use Keras and TensorFlow in R.\n\n1. **Define**: Model, Sequential model, Multi-GPU model\n2. **Compile**: Optimizer, Loss, Metrics\n3. **Fit**: Batch size, Epochs, Validation split\n4. **Evaluate**: Evaluate, Plot\n5. **Predict**: Classes, Probability\n\nRead more at:\\\n\\\n\n\n### Installation\n\nThe keras R package uses the Python keras library.\nYou can install all the prerequisites directly from R: .\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(keras)\ninstall_keras()\n```\n:::\n\n\nSee `?install_keras` for GPU instructions.\n\nThis installs the required libraries in an Anaconda environment or virtual environment `r-tensorflow`.\n\n### Training an Image Recognizer on MNIST Data\n\nThe \"Hello, World!\" of deep learning\n\n\n::: {.cell}\n\n```{.r .cell-code}\n# input layer: use MNIST images\nmnist <- dataset_mnist()\nx_train <- mnist$train$x\ny_train <- mnist$train$y \nx_test <- mnist$test$x\ny_test <- mnist$test$y\n\n# reshape and rescale\nx_train <- array_reshape(x_train, c(nrow(x_train), 784)) \nx_test <- array_reshape(x_test, c(nrow(x_test), 784)) \nx_train <- x_train / 255\nx_test <- x_test / 255\n\ny_train <- to_categorical(y_train, 10) \ny_test <- to_categorical(y_test, 10)\n\n# defining the model and layers\nmodel <- keras_model_sequential() \nmodel %>%\n layer_dense(units = 256, activation = 'relu', input_shape = c(784)) %>%\n layer_dropout(rate = 0.4) %>% \n layer_dense(units = 128, activation = 'relu') %>% \n layer_dense(units = 10, activation = 'softmax')\n \n# compile (define loss and optimizer)\nmodel %>%\n compile(\n loss = 'categorical_crossentropy', \n optimizer = optimizer_rmsprop(), \n metrics = c('accuracy')\n)\n\n# train (fit)\nmodel %>% fit(\n x_train, y_train,\n epochs = 30, batch_size = 128, \n validation_split = 0.2\n)\n\nmodel %>% evaluate(x_test, y_test) \nmodel %>% predict_classes(x_test)\n```\n:::\n\n\n## Working with keras models\n\n### Define a Model\n\n- `keras_model()`: Keras Model.\n\n- `keras_model_sequential()`: Keras Model composed of a linear stack of layers.\n\n- `multi_gpu_model()`: Replicates a model on different GPUs.\n\n### Compile a Model\n\n- `compile(object, optimizer, loss, metrics = NULL)`: Configure a Keras model for training.\n\n### Fit a Model\n\n- `fit(object, x = NULL, y = NULL, batch_size = NULL, epochs = 10, verbose = 1, callbacks = NULL, ...)`: Train a Keras model for a fixed number of epochs (iterations).\n\n- `fit_generator()`: Fits the model on data yielded batch-by-batch by a generator.\n\n- `train_on_batch()`; `test_on_batch()`: Single gradient update or model evaluation over one batch of samples.\n\n### Evaluate a Model\n\n- `evaluate(object, x = NULL, y = NULL, batch_size = NULL)`: Evaluate a Keras model.\n\n- `evaluate_generator()`: Evaluates the model on a data generator.\n\n### Predict\n\n- `predict()`: Generate predictions from a Keras model.\n\n- `predict_proba()`; `predict_classes()`: Generates probability or class probability predictions for the input samples.\n\n- `predict_on_batch()`: Returns predictions for a single batch of samples.\n\n- `predict_generator()`: Generates predictions for the input samples from a data generator.\n\n### Other Model Operations\n\n- `summary()`: Print a summary of a Keras model.\n\n- `export_savedmodel()`: Export a saved model.\n\n- `get_layer()`: Retrieves a layer based on either its name (unique) or index.\n\n- `pop_layer()`: Remove the last layer in a model.\n\n- `save_model_hdf5()`; `load_model_hdf5()`: Save/Load models using HDF5 files.\n\n- `serialize_model()`; `unserialize_model()`: Serialize a model to an R object.\n\n- `clone_model()`: Clone a model instance.\n\n- `freeze_weights()`; `unfreeze_weights()`\n\n### Core Layers\n\n- `layer_input()`: Input layer.\n\n- `layer_dense()`: Add a densely-connected NN layer to an output.\n\n- `layer_activation()`: Apply an activation function to an output.\n\n- `layer_dropout()`: Applies Dropout to the input.\n\n- `layer_reshape()`: Reshapes an output to a certain shape.\n\n- `layer_permute()`: Permute the dimensions of an input according to a given pattern.\n\n- `layer_repeat_vector()`: Repeats the input n times.\n\n- `layer_lambda(object, f)`: Wraps arbitrary expression as a layer.\n\n- `layer_activity_regularization()`: Layer that applies an update to the cost function based input activity.\n\n- `layer_masking()`: Masks a sequence by using a mask value to skip timesteps.\n\n- `layer_flatten()`: Flattens an input.\n\n\n\n## More layers\n\n### Convolutional Layers\n\n- `layer_conv_1d()`: 1D, e.g. temporal convolution.\n\n- `layer_conv_2d_transpose()`: Transposed 2D (deconvolution).\n\n- `layer_conv_2d()` : 2D, e.g. spatial convolution over images.\n\n- `layer_conv_3d_transpose()`: Transposed 3D (deconvolution).\n\n- `layer_conv_3d()`: 3D, e.g. spatial convolution over volumes.\n\n- `layer_conv_lstm_2d()`: Convolutional LSTM.\n\n- `layer_separable_conv_2d()`: Depthwise separable 2D.\n\n- `layer_upsampling_1d()`; `layer_upsampling_2d()`; `layer_upsampling_3d()`: Upsampling layer.\n\n- `layer_zero_padding_1d()`; `layer_zero_padding_2d()`; `layer_zero_padding_3d()`: Zero-padding layer.\n\n- `layer_cropping_1d()`; `layer_cropping_2d()`; `layer_cropping_3d()`: Cropping layer.\n\n### Pooling Layers\n\n- `layer_max_pooling_1d()`; `layer_max_pooling_2d()`; `layer_max_pooling_3d()`: Maximum pooling for 1D to 3D.\n\n- `layer_average_pooling_1d()`; `layer_average_pooling_2d()`; `layer_average_pooling_3d()`: Average pooling for 1D to 3D.\n\n- `layer_global_max_pooling_1d()`; `layer_global_max_pooling_2d()`; `layer_global_max_pooling_3d()`: Global maximum pooling.\n\n- `layer_global_average_pooling_1d()`; `layer_global_average_pooling_2d()`; `layer_global_average_pooling_3d()`: Global average pooling.\n\n### Activation Layers\n\n- `layer_activation(object, activation)`: Apply an activation function to an output.\n\n- `layer_activation_leaky_relu()`: Leaky version of a rectified linear unit.\n\n- `layer_activation_parametric_relu()`: Parametric rectified linear unit.\n\n- `layer_activation_thresholded_relu()`: Thresholded rectified linear unit.\n\n- `layer_activation_elu()`: Exponential linear unit.\n\n### Dropout Layers\n\n- `layer_dropout()`: Applies dropout to the input.\n\n- `layer_spatial_dropout_1d()`; `layer_spatial_dropout_2d()`; `layer_spatial_dropout_3d()`: Spatial 1D to 3D version of dropout\n\n### Recurrent Layers\n\n- `layer_simple_rnn()`: Fully-connected RNN where the output is to be fed back to input.\n\n- `layer_gru()`: Gated recurrent unit - Cho et al.\n\n- `layer_cudnn_gru()`: Fast GRU implementation backed by CuDNN.\n\n- `layer_lstm()`: Long-Short Term Memory unit - Hochreiter 1997.\n\n- `layer_cudnn_lstm()`: Fast LSTM implementation backed by CuDNN.\n\n### Locally Connected Layers\n\n- `layer_locally_connected_1d()`; `layer_locally_connected_2d()`: Similar to convolution, but weights are not shared, i.e. different filters for each patch.\n\n## Preprocessing\n\n### Sequence Preprocessing\n\n- `pad_sequences()`: Pads each sequence to the same length (length of the longest sequence).\n\n- `skipgrams()`: Generates skipgram word pairs.\n\n- `make_sampling_table()`: Generates word rank-based probabilistic sampling table.\n\n### Text Preprocessing\n\n- `text_tokenizer()`: Text tokenization utility.\n\n- `fit_text_tokenizer()`: Update tokenizer internal vocabulary.\n\n- `save_text_tokenizer()`; `load_text_tokenizer()`: Save a text tokenizer to an external file.\n\n- `texts_to_sequences()`; `texts_to_sequences_generator()`: Transforms each text in texts to sequence of integers.\n\n- `texts_to_matrix()`; `sequences_to_matrix()`: Convert a list of sequences into a matrix.\n\n- `text_one_hot()`: One-hot encode text to word indices.\n\n- `text_hashing_trick()`: Converts a text to a sequence of indexes in a fixed-size hashing space.\n\n- `text_to_word_sequence()`: Convert text to a sequence of words (or tokens).\n\n### Image Proprocessing\n\n- `image_load()`: Loads an image into PIL format.\n\n- `flow_images_from_data()`; `flow_images_from_directory()`: Generates batches of augmented/normalized data from images and labels, or a directory.\n\n- `image_data_generator()`: Generate minibatches of image data with real-time data augmentation.\n\n- `fit_image_data_generator()`: Fit image data generator internal statistics to some sample data.\n\n- `generator_next()`: Retrieve the next item.\n\n- `image_to_array()`; `image_array_resize()`; `image_array_save()`: 3D array representation.\n\n## Pre-trained models\n\nKeras applications are deep learning models that are made available alongside pre-trained weights.\nThese models can be used for prediction, feature extraction, and fine-tuning.\n\n- `application_xception()`; `xception_preprocess_input()`: Xception v1 model.\n\n- `application_inception_v3()`; `inception_v3_preprocess_input()`: Inception v3 model, with weights pre-trained on ImageNet.\n\n- `application_inception_resnet_v2()`; `inception_resnet_v2_preprocess_input()`: Inception-ResNet v2 model, with weights trained on ImageNet.\n\n- `application_vgg16()`; `application_vgg19()`: VGG16 and VGG19 models.\n\n- `application_resnet50()`: ResNet50 model.\n\n- `application_mobilenet()`; `mobilenet_preprocess_input()`; `mobilenet_decode_predictions()`; `mobilenet_load_model_hdf5()`: MobileNet model architecture.\n\nImageNet is a large database of images with labels, extensively used for deep learning.\n\n- `imagenet_preprocess_input()`; `imagenet_decode_predictions()`: Preprocesses a tensor encoding a batch of images for ImageNet, and decodes predictions.\n\n## Callbacks\n\nA callback is a set of functions to be applied at given stages of the training procedure.\nYou can use callbacks to get a view on internal states and statistics of the model during training.\n\n- `allback_early_stopping()`: Stop training when a monitored quantity has stopped improving.\n\n- `callback_learning_rate_scheduler()`: Learning rate scheduler.\n\n- `callback_tensorboard()`: TensorBoard basic visualizations.\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [tensorflow.rstudio.com](https://tensorflow.rstudio.com/).\n\nUpdated: 2023-06.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"keras\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '2.11.1'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", "supporting": [], "filters": [ "rmarkdown/pagebreak.lua" diff --git a/_freeze/html/lubridate/execute-results/html.json b/_freeze/html/lubridate/execute-results/html.json index f566dcf5..09f6697a 100644 --- a/_freeze/html/lubridate/execute-results/html.json +++ b/_freeze/html/lubridate/execute-results/html.json @@ -1,7 +1,7 @@ { - "hash": "c0519eac7a984aa1b41db64a6ef1beaa", + "hash": "a6baed88ece4b5becc66a118f98cbfce", "result": { - "markdown": "---\ntitle: \"Dates and times with lubridate :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: false\n---\n\n::: {.cell .column-margin}\n\"\"\n

\n

Download PDF

\n\n
\n

Translations (PDF)

\n* Russian\n* Spanish\n* Ukrainian\n* Vietnamese\n:::\n\n\n## Date-times\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(lubridate)\n```\n:::\n\n\n\n\nA **date-time** is a point on the timeline, stored as the number of seconds since 1970-01-01 00:00:00 UTC\n\n\n::: {.cell}\n\n```{.r .cell-code}\ndt <- as_datetime(1511870400)\n```\n:::\n\n\nA **date** is a day stored as the number of days since 1970-01-01\n\n\n::: {.cell}\n\n```{.r .cell-code}\nd <- as_date(17498)\n```\n:::\n\n\nAn hms is a **time** stored as the number of seconds since 00:00:00\n\n\n::: {.cell}\n\n```{.r .cell-code}\nt <- hms::as_hms(85)\n```\n:::\n\n\n### Parse Date-Times\n\nConvert strings or numbers to date-times\n\n1. Identify the order of the year (**y**), month (**m**), day (**d**), hour (**h**), minute (**m**) and second (**s**) elements in your data.\n\n2. Use the function below whose name replicates the order.\n Each accepts a `tz` argument to set the time zone, e.g. `ymd(x, tz = \"UTC\")`.\n\n- `ymd_hms()`, `ymd_hm()`, `ymd_h()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n ymd_hms(\"2017-11-28T14:02:00\")\n ```\n :::\n\n\n- `ydm_hms()`, `ydm_hm()`, `ydm_h()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n ydm_hms(\"2017-22-12 10:00:00\")\n ```\n :::\n\n\n- `mdy_hms()`, `mdy_hm()`, `mdy_h()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mdy_hms(\"11/28/2017 1:02:03\")\n ```\n :::\n\n\n- `dmy_hms()`, `dmy_hm()`, `dmy_h()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n dmy_hms(\"1 Jan 2017 23:59:59\")\n ```\n :::\n\n\n- `ymd()`, `ydm()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n ymd(20170131)\n ```\n :::\n\n\n- `mdy()`, `myd()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mdy(\"July 4th, 2000\")\n ```\n :::\n\n\n- `dmy()`, `dym()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n dmy(\"4th of July '99\")\n ```\n :::\n\n\n- `yq()`: Q for quarter.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n yq(\"2001: Q3\")\n ```\n :::\n\n\n- `my()`, `ym()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n my(\"07-2020\")\n ```\n :::\n\n\n- `hms::hms()`: Also `lubridate::hms()`, `hm()`, and `ms()`, which return periods\\*.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n hms::hms(seconds = 0, minutes = 1, hours = 2)\n ```\n :::\n\n\n- `date_decimal(decimal, tz = \"UTC\")`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n date_decimal(2017.5)\n ```\n :::\n\n\n- `now(tzone = \"\")`: Current time in tz (defaults to system tz).\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n now()\n ```\n :::\n\n\n- `today(tzone = \"\")`: Current date in a tz (defaults to system tz).\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n today()\n ```\n :::\n\n\n- `fast_strptime()`: Faster strptime.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fast_strptime(\"9/1/01\", \"%y/%m/%d\")\n ```\n :::\n\n\n- `parse_date_time()`: Easier strptime.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n parse_date_time(\"09-01-01\", \"ymd\")\n ```\n :::\n\n\n### Get and Set Components\n\nUse an accessor function to get a component.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nd\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] \"2017-11-28\"\n```\n:::\n\n```{.r .cell-code}\nday(d)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 28\n```\n:::\n:::\n\n\nAssign into an accessor function to change a component in place.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nday(d) <- 1\nd\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] \"2017-11-01\"\n```\n:::\n:::\n\n\n- `date(x)`: Date component.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n date(dt)\n ```\n :::\n\n\n- `year(x)`: Year.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n year(dt)\n ```\n :::\n\n\n- `isoyear(x)`: The ISO 8601 year.\n\n- `epiyear(x)`: Epidemiological year.\n\n- `month(x, label, abbr)`: Month.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n month(dt)\n ```\n :::\n\n\n- `day(x)`: Day of the month.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n day(dt)\n ```\n :::\n\n\n- `wday(x, label, abbr)`: Day of week.\n\n- `qday(x)`: Day of quarter.\n\n- `hour(x)`: Hour.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n hour(dt)\n ```\n :::\n\n\n- `minute(x)`: Minutes.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n minute(dt)\n ```\n :::\n\n\n- `second(x)`: Seconds.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n second(dt)\n ```\n :::\n\n\n- `tz(x)`: Time zone.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n tz(dt)\n ```\n :::\n\n\n- `week(x)`: Week of the year.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n week(dt)\n ```\n :::\n\n\n- `isoweek()`: ISO 8601 week.\n\n- `epiweek()`: Epidemiological week.\n\n- `quarter(x)`: Quarter.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n quarter(dt)\n ```\n :::\n\n\n- `semester(x, with_year = FALSE)`: Semester.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n semester(dt)\n ```\n :::\n\n\n- `am(x)`: Is it in the am?\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n am(dt)\n ```\n :::\n\n\n- `pm(x)`: Is it in the pm?\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pm(dt)\n ```\n :::\n\n\n- `dst(x)`: Is it daylight savings?\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n dst(d)\n ```\n :::\n\n\n- `leap_year(x)`: Is it a leap year?\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n leap_year(d)\n ```\n :::\n\n\n- `update(object, ..., simple = FALSE)`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n update(dt, mday = 2, hour = 1)\n ```\n :::\n\n\n## Round Date-times\n\n- `floor_date(x, unit = \"second\")`: Round down to nearest unit.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n floor_date(dt, unit = \"month\")\n ```\n :::\n\n\n- `round_date(x, unit = \"second\")`: Round to nearest unit.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n round_date(dt, unit = \"month\")\n ```\n :::\n\n\n- `ceiling_date(x, unit = \"second\")`: Round up to the nearest unit.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n ceiling_date(dt, unit = \"month\")\n ```\n :::\n\n\nValid units are second, minute, hour, day, week, month, bimonth, quarter, season, halfyear and year.\n\n- `rollback(dates, roll_to_first = FALSE, preserve_hms = TRUE)`: Roll back to last day of previous month.\n Also `rollforward()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n rollback(dt)\n ```\n :::\n\n\n## Stamp Date-times\n\n`stamp()`: Derive a template from an example string and return a new function that will apply the template to date-times.\nAlso `stamp_date()` and `stamp_time()`.\n\n1. Derive a template, create a function\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n sf <- stamp(\"Created Sunday, Jan 17, 1999 3:34\")\n ```\n :::\n\n\n2. Apply the template to dates\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n sf(ymd(\"2010-04-05\"))\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n [1] \"Created Monday, Apr 05, 2010 00:00\"\n ```\n :::\n :::\n\n\n**Tip: use a date with day \\> 12**\n\n## Time Zones\n\nR recognizes \\~600 time zones.\nEach encodes the time zone, Daylight Savings Time, and historical calendar variations for an area.\nR assigns *one* time zone per vector.\n\nUse the `UTC` time zone to avoid Daylight Savings.\n\n- `OlsonNames()`: Returns a list of valid time zone names.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n OlsonNames()\n ```\n :::\n\n\n- `Sys.timezone()`: Gets current time zone.\n\n- `with_tz(time, tzone = \"\")`: Get the **same date-time** in a new time zone (a new clock time).\n Also `local_time(dt, tz, units)`.\n For example, 4:00 Pacific becomes 5:00 Mountain, or 6:00 Central, or 7:00 Eastern.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n with_tz(dt, \"US/Pacific\")\n ```\n :::\n\n\n- `force_tz(time, tzone = \"\")`: Get the **same clock time** in a new time zone (a new date-time).\n Also `force_tzs()`.\n For example, 7:00 Pacific becomes 7:00 Mountain, or 7:00 Central, or 7:00 Eastern.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n force_tz(dt, \"US/Pacific\")\n ```\n :::\n\n\n## Math with Date-times\n\nLubridate provides three classes of timespans to facilitate math with dates and date-times.\n\nMath with date-times relies on the **timeline**, which behaves inconsistently.\nConsider how the timeline behaves during:\n\n- A normal day:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nnor <- ymd_hms(\"2018-01-01 01:30:00\", tz = \"US/Eastern\")\n```\n:::\n\n\n- The start of daylight savings (spring forward):\n\n\n::: {.cell}\n\n```{.r .cell-code}\ngap <- ymd_hms(\"2018-03-11 01:30:00\", tz = \"US/Eastern\")\n```\n:::\n\n\n- The end of daylight savings (fall back):\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlap <- ymd_hms(\"2018-11-04 00:30:00\", tz = \"US/Eastern\")\n```\n:::\n\n\n- Leap years and leap seconds:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nleap <- ymd(\"2019-03-01\")\n```\n:::\n\n\n**Periods** track changes in clock times, which ignore time line irregularities.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nnor + minutes(90)\ngap + minutes(90)\nlap + minutes(90)\nleap + years(1)\n```\n:::\n\n\n**Durations** track the passage of physical time, which deviates from clock time when irregularities occur.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nnor + dminutes(90)\ngap + dminutes(90)\nlap + dminutes(90)\nleap + dyears(1)\n```\n:::\n\n\n**Intervals** represent specific intervals of the timeline, bounded by start and end date-times.\n\n\n::: {.cell}\n\n```{.r .cell-code}\ninterval(nor, nor + minutes(90))\ninterval(gap, gap + minutes(90))\ninterval(lap, lap + minutes(90))\ninterval(leap, leap + years(1))\n```\n:::\n\n\nNot all years are 365 days due to **leap days**.\nNot all minutes are 60 seconds due to **leap seconds**.\nIt is possible to create an imaginary date by adding **months**, e.g.\nFebruary 31st.\n\n\n::: {.cell}\n\n```{.r .cell-code}\njan31 <- ymd(20180131)\njan31 + months(1)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] NA\n```\n:::\n:::\n\n\n`%m+%` and `%m-%` will roll imaginary dates to the last day of the previous month.\n\n\n::: {.cell}\n\n```{.r .cell-code}\njan31 %m+% months(1)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] \"2018-02-28\"\n```\n:::\n:::\n\n\n`add_with_rollback(e1, e2, roll_to_first = TRUE)` will roll imaginary dates to the first day of the new month.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nadd_with_rollback(jan31, months(1), roll_to_first = TRUE)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] \"2018-03-01\"\n```\n:::\n:::\n\n\n### Periods\n\nAdd or subtract periods to model events that happen a specific clock times, the the NYSE opening bell.\n\nMake a period with the name of a time unit **pluralized**, e.g.\n\n\n::: {.cell}\n\n```{.r .cell-code}\np <- months(3) + days(12)\n\n# Shows the number of months, number of days, etc.\np\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] \"3m 12d 0H 0M 0S\"\n```\n:::\n:::\n\n\n- `years(x = 1)`: x years.\n\n- `months(x = 1)`: x months.\n\n- `weeks(x = 1)`: x weeks.\n\n- `days(x = 1)`: x days.\n\n- `hours(x = 1)`: x hours.\n\n- `minutes(x = 1)`: x minutes.\n\n- `seconds(x = 1)`: x seconds.\n\n- `milliseconds(x = 1)`: x milliseconds.\n\n- `microseconds(x = 1)`: x microseconds.\n\n- `nanoseconds(x = 1)`: x nanoseconds.\n\n- `picoseconds(x = 1)`: x picoseconds.\n\n- `period(num = NULL, units = \"second\", ...)`: An automation friendly period constructor.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n period(5, unit = \"years\")\n ```\n :::\n\n\n- `as.period(x, unit)`: Coerce a timespan to a period, optionally in the specified units.\n Also `is.period()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n as.period(p)\n ```\n :::\n\n\n- `period_to_seconds(x)`: Convert a period to the \"standard\" number of seconds implied by the period.\n Also `seconds_to_period()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n period_to_seconds(p)\n ```\n :::\n\n\n### Durations\n\nAdd or subtract durations to model physical processes, like battery life.\nDurations are stored as seconds, the only time unit with a consistent length.\n**Difftimes** are a class of durations found in base R.\n\nMake a duration with the name of a period prefixed with a *d*, e.g.\n\n\n::: {.cell}\n\n```{.r .cell-code}\ndd <- ddays(14)\n\n# Shows the exact length in seconds, and the equivalent in common units\ndd\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] \"1209600s (~2 weeks)\"\n```\n:::\n:::\n\n\n- `dyears(x = 1)`: 31536000x seconds.\n\n- `dmonths(x = 1)`: 2629800x seconds.\n\n- `dweeks(x = 1)`: 604800x seconds.\n\n- `ddays(x = 1)`: 86400x seconds.\n\n- `dhours(x = 1)`: 3600x seconds.\n\n- `dminutes(x = 1)`: 60x seconds.\n\n- `dseconds(x = 1)`: x seconds.\n\n- `dmilliseconds(x = 1)`: x \\* 10^-3^ seconds.\n\n- `dmicroseconds(x = 1)`: x \\* 10^-6^ seconds.\n\n- `dnanoseconds(x = 1)`: x \\* 10^-9^ seconds.\n\n- `dpicoseconds(x = 1)`: x \\* 10^-12^ seconds.\n\n- `duration(num = NULL, units = \"second\", ...)`: An automation friendly duration constructor.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n duration(5, unit = \"years\")\n ```\n :::\n\n\n- `as.duration(x, ...)`: Coerce a timespan to a duration.\n Also `is.duration()`, `is.difftime()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n as.duration(p)\n ```\n :::\n\n\n- `make_difftime(x)`: Make diffime with the specified number of units.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n make_difftime(99999)\n ```\n :::\n\n\n### Intervals\n\nDivide an interval by a duration to determine its physical length, divide by an interval by a period to determine its implied length in clock time.\n\nMake an interval with `interval()` or `%--%`, e.g.\n\n\n::: {.cell}\n\n```{.r .cell-code}\ni <- interval(ymd(\"2017-01-01\"), d)\ni\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 2017-01-01 UTC--2017-11-01 UTC\n```\n:::\n\n```{.r .cell-code}\n# Shows the exact length in seconds, and the equivalent in common units\nj <- d %--% ymd(\"2017-12-31\")\nj\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 2017-11-01 UTC--2017-12-31 UTC\n```\n:::\n:::\n\n\n- `a %within% b`: Does interval or dte0time `a` fall within interval `b`?\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n now() %within% i\n ```\n :::\n\n\n- `int_start(int)`: Access/set the start date-time of an interval.\n Also `int_end()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n int_start(i) <- now()\n int_start(i)\n ```\n :::\n\n\n- `int_aligns(int1, int2)`: Do two intervals share a boundary?\n Also `int_overlaps()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n int_aligns(i, j)\n ```\n :::\n\n\n- `int_diff(times)`: Make the intervals that occur between the date-times in a vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n v <- c(dt, dt + 100, dt + 1000)\n int_diff(v)\n ```\n :::\n\n\n- `int_flip(int)`: Reverse the direction of an interval.\n Also `int_standardize()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n int_flip(i)\n ```\n :::\n\n\n- `int_length(int)`: Length in seconds.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n int_length(i)\n ```\n :::\n\n\n- `int_shift(int, by)`: Shifts an interval up or down the timeline by a timespan.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n int_shift(i, days(-1))\n ```\n :::\n\n\n- `as.interval(x, start, ...)`: Coerce a timespan to an interval with the start date-time.\n Also `is.interval()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n as.interval(days(-1), start = now())\n ```\n :::\n\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [lubridate.tidyverse.org](https://lubridate.tidyverse.org).\n\nUpdated: 2023-05.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"lubridate\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.9.2'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", + "markdown": "---\ntitle: \"Dates and times with lubridate :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: false\n---\n\n::: {.cell .column-margin}\n\"Hex\n

\n

Download PDF

\n\"\"/\n
\n

Translations (PDF)

\n* Russian\n* Spanish\n* Ukrainian\n* Vietnamese\n:::\n\n\n## Date-times\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(lubridate)\n```\n:::\n\n\n\n\nA **date-time** is a point on the timeline, stored as the number of seconds since 1970-01-01 00:00:00 UTC\n\n\n::: {.cell}\n\n```{.r .cell-code}\ndt <- as_datetime(1511870400)\n```\n:::\n\n\nA **date** is a day stored as the number of days since 1970-01-01\n\n\n::: {.cell}\n\n```{.r .cell-code}\nd <- as_date(17498)\n```\n:::\n\n\nAn hms is a **time** stored as the number of seconds since 00:00:00\n\n\n::: {.cell}\n\n```{.r .cell-code}\nt <- hms::as_hms(85)\n```\n:::\n\n\n### Parse Date-Times\n\nConvert strings or numbers to date-times\n\n1. Identify the order of the year (**y**), month (**m**), day (**d**), hour (**h**), minute (**m**) and second (**s**) elements in your data.\n\n2. Use the function below whose name replicates the order.\n Each accepts a `tz` argument to set the time zone, e.g. `ymd(x, tz = \"UTC\")`.\n\n- `ymd_hms()`, `ymd_hm()`, `ymd_h()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n ymd_hms(\"2017-11-28T14:02:00\")\n ```\n :::\n\n\n- `ydm_hms()`, `ydm_hm()`, `ydm_h()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n ydm_hms(\"2017-22-12 10:00:00\")\n ```\n :::\n\n\n- `mdy_hms()`, `mdy_hm()`, `mdy_h()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mdy_hms(\"11/28/2017 1:02:03\")\n ```\n :::\n\n\n- `dmy_hms()`, `dmy_hm()`, `dmy_h()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n dmy_hms(\"1 Jan 2017 23:59:59\")\n ```\n :::\n\n\n- `ymd()`, `ydm()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n ymd(20170131)\n ```\n :::\n\n\n- `mdy()`, `myd()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mdy(\"July 4th, 2000\")\n ```\n :::\n\n\n- `dmy()`, `dym()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n dmy(\"4th of July '99\")\n ```\n :::\n\n\n- `yq()`: Q for quarter.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n yq(\"2001: Q3\")\n ```\n :::\n\n\n- `my()`, `ym()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n my(\"07-2020\")\n ```\n :::\n\n\n- `hms::hms()`: Also `lubridate::hms()`, `hm()`, and `ms()`, which return periods\\*.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n hms::hms(seconds = 0, minutes = 1, hours = 2)\n ```\n :::\n\n\n- `date_decimal(decimal, tz = \"UTC\")`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n date_decimal(2017.5)\n ```\n :::\n\n\n- `now(tzone = \"\")`: Current time in tz (defaults to system tz).\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n now()\n ```\n :::\n\n\n- `today(tzone = \"\")`: Current date in a tz (defaults to system tz).\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n today()\n ```\n :::\n\n\n- `fast_strptime()`: Faster strptime.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fast_strptime(\"9/1/01\", \"%y/%m/%d\")\n ```\n :::\n\n\n- `parse_date_time()`: Easier strptime.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n parse_date_time(\"09-01-01\", \"ymd\")\n ```\n :::\n\n\n### Get and Set Components\n\nUse an accessor function to get a component.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nd\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] \"2017-11-28\"\n```\n:::\n\n```{.r .cell-code}\nday(d)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 28\n```\n:::\n:::\n\n\nAssign into an accessor function to change a component in place.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nday(d) <- 1\nd\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] \"2017-11-01\"\n```\n:::\n:::\n\n\n- `date(x)`: Date component.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n date(dt)\n ```\n :::\n\n\n- `year(x)`: Year.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n year(dt)\n ```\n :::\n\n\n- `isoyear(x)`: The ISO 8601 year.\n\n- `epiyear(x)`: Epidemiological year.\n\n- `month(x, label, abbr)`: Month.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n month(dt)\n ```\n :::\n\n\n- `day(x)`: Day of the month.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n day(dt)\n ```\n :::\n\n\n- `wday(x, label, abbr)`: Day of week.\n\n- `qday(x)`: Day of quarter.\n\n- `hour(x)`: Hour.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n hour(dt)\n ```\n :::\n\n\n- `minute(x)`: Minutes.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n minute(dt)\n ```\n :::\n\n\n- `second(x)`: Seconds.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n second(dt)\n ```\n :::\n\n\n- `tz(x)`: Time zone.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n tz(dt)\n ```\n :::\n\n\n- `week(x)`: Week of the year.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n week(dt)\n ```\n :::\n\n\n- `isoweek()`: ISO 8601 week.\n\n- `epiweek()`: Epidemiological week.\n\n- `quarter(x)`: Quarter.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n quarter(dt)\n ```\n :::\n\n\n- `semester(x, with_year = FALSE)`: Semester.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n semester(dt)\n ```\n :::\n\n\n- `am(x)`: Is it in the am?\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n am(dt)\n ```\n :::\n\n\n- `pm(x)`: Is it in the pm?\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pm(dt)\n ```\n :::\n\n\n- `dst(x)`: Is it daylight savings?\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n dst(d)\n ```\n :::\n\n\n- `leap_year(x)`: Is it a leap year?\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n leap_year(d)\n ```\n :::\n\n\n- `update(object, ..., simple = FALSE)`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n update(dt, mday = 2, hour = 1)\n ```\n :::\n\n\n## Round Date-times\n\n- `floor_date(x, unit = \"second\")`: Round down to nearest unit.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n floor_date(dt, unit = \"month\")\n ```\n :::\n\n\n- `round_date(x, unit = \"second\")`: Round to nearest unit.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n round_date(dt, unit = \"month\")\n ```\n :::\n\n\n- `ceiling_date(x, unit = \"second\")`: Round up to the nearest unit.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n ceiling_date(dt, unit = \"month\")\n ```\n :::\n\n\nValid units are second, minute, hour, day, week, month, bimonth, quarter, season, halfyear and year.\n\n- `rollback(dates, roll_to_first = FALSE, preserve_hms = TRUE)`: Roll back to last day of previous month.\n Also `rollforward()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n rollback(dt)\n ```\n :::\n\n\n## Stamp Date-times\n\n`stamp()`: Derive a template from an example string and return a new function that will apply the template to date-times.\nAlso `stamp_date()` and `stamp_time()`.\n\n1. Derive a template, create a function\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n sf <- stamp(\"Created Sunday, Jan 17, 1999 3:34\")\n ```\n :::\n\n\n2. Apply the template to dates\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n sf(ymd(\"2010-04-05\"))\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n [1] \"Created Monday, Apr 05, 2010 00:00\"\n ```\n :::\n :::\n\n\n**Tip: use a date with day \\> 12**\n\n## Time Zones\n\nR recognizes \\~600 time zones.\nEach encodes the time zone, Daylight Savings Time, and historical calendar variations for an area.\nR assigns *one* time zone per vector.\n\nUse the `UTC` time zone to avoid Daylight Savings.\n\n- `OlsonNames()`: Returns a list of valid time zone names.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n OlsonNames()\n ```\n :::\n\n\n- `Sys.timezone()`: Gets current time zone.\n\n- `with_tz(time, tzone = \"\")`: Get the **same date-time** in a new time zone (a new clock time).\n Also `local_time(dt, tz, units)`.\n For example, 4:00 Pacific becomes 5:00 Mountain, or 6:00 Central, or 7:00 Eastern.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n with_tz(dt, \"US/Pacific\")\n ```\n :::\n\n\n- `force_tz(time, tzone = \"\")`: Get the **same clock time** in a new time zone (a new date-time).\n Also `force_tzs()`.\n For example, 7:00 Pacific becomes 7:00 Mountain, or 7:00 Central, or 7:00 Eastern.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n force_tz(dt, \"US/Pacific\")\n ```\n :::\n\n\n## Math with Date-times\n\nLubridate provides three classes of timespans to facilitate math with dates and date-times.\n\nMath with date-times relies on the **timeline**, which behaves inconsistently.\nConsider how the timeline behaves during:\n\n- A normal day:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nnor <- ymd_hms(\"2018-01-01 01:30:00\", tz = \"US/Eastern\")\n```\n:::\n\n\n- The start of daylight savings (spring forward):\n\n\n::: {.cell}\n\n```{.r .cell-code}\ngap <- ymd_hms(\"2018-03-11 01:30:00\", tz = \"US/Eastern\")\n```\n:::\n\n\n- The end of daylight savings (fall back):\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlap <- ymd_hms(\"2018-11-04 00:30:00\", tz = \"US/Eastern\")\n```\n:::\n\n\n- Leap years and leap seconds:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nleap <- ymd(\"2019-03-01\")\n```\n:::\n\n\n**Periods** track changes in clock times, which ignore time line irregularities.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nnor + minutes(90)\ngap + minutes(90)\nlap + minutes(90)\nleap + years(1)\n```\n:::\n\n\n**Durations** track the passage of physical time, which deviates from clock time when irregularities occur.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nnor + dminutes(90)\ngap + dminutes(90)\nlap + dminutes(90)\nleap + dyears(1)\n```\n:::\n\n\n**Intervals** represent specific intervals of the timeline, bounded by start and end date-times.\n\n\n::: {.cell}\n\n```{.r .cell-code}\ninterval(nor, nor + minutes(90))\ninterval(gap, gap + minutes(90))\ninterval(lap, lap + minutes(90))\ninterval(leap, leap + years(1))\n```\n:::\n\n\nNot all years are 365 days due to **leap days**.\nNot all minutes are 60 seconds due to **leap seconds**.\nIt is possible to create an imaginary date by adding **months**, e.g.\nFebruary 31st.\n\n\n::: {.cell}\n\n```{.r .cell-code}\njan31 <- ymd(20180131)\njan31 + months(1)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] NA\n```\n:::\n:::\n\n\n`%m+%` and `%m-%` will roll imaginary dates to the last day of the previous month.\n\n\n::: {.cell}\n\n```{.r .cell-code}\njan31 %m+% months(1)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] \"2018-02-28\"\n```\n:::\n:::\n\n\n`add_with_rollback(e1, e2, roll_to_first = TRUE)` will roll imaginary dates to the first day of the new month.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nadd_with_rollback(jan31, months(1), roll_to_first = TRUE)\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] \"2018-03-01\"\n```\n:::\n:::\n\n\n### Periods\n\nAdd or subtract periods to model events that happen a specific clock times, the the NYSE opening bell.\n\nMake a period with the name of a time unit **pluralized**, e.g.\n\n\n::: {.cell}\n\n```{.r .cell-code}\np <- months(3) + days(12)\n\n# Shows the number of months, number of days, etc.\np\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] \"3m 12d 0H 0M 0S\"\n```\n:::\n:::\n\n\n- `years(x = 1)`: x years.\n\n- `months(x = 1)`: x months.\n\n- `weeks(x = 1)`: x weeks.\n\n- `days(x = 1)`: x days.\n\n- `hours(x = 1)`: x hours.\n\n- `minutes(x = 1)`: x minutes.\n\n- `seconds(x = 1)`: x seconds.\n\n- `milliseconds(x = 1)`: x milliseconds.\n\n- `microseconds(x = 1)`: x microseconds.\n\n- `nanoseconds(x = 1)`: x nanoseconds.\n\n- `picoseconds(x = 1)`: x picoseconds.\n\n- `period(num = NULL, units = \"second\", ...)`: An automation friendly period constructor.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n period(5, unit = \"years\")\n ```\n :::\n\n\n- `as.period(x, unit)`: Coerce a timespan to a period, optionally in the specified units.\n Also `is.period()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n as.period(p)\n ```\n :::\n\n\n- `period_to_seconds(x)`: Convert a period to the \"standard\" number of seconds implied by the period.\n Also `seconds_to_period()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n period_to_seconds(p)\n ```\n :::\n\n\n### Durations\n\nAdd or subtract durations to model physical processes, like battery life.\nDurations are stored as seconds, the only time unit with a consistent length.\n**Difftimes** are a class of durations found in base R.\n\nMake a duration with the name of a period prefixed with a *d*, e.g.\n\n\n::: {.cell}\n\n```{.r .cell-code}\ndd <- ddays(14)\n\n# Shows the exact length in seconds, and the equivalent in common units\ndd\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] \"1209600s (~2 weeks)\"\n```\n:::\n:::\n\n\n- `dyears(x = 1)`: 31536000x seconds.\n\n- `dmonths(x = 1)`: 2629800x seconds.\n\n- `dweeks(x = 1)`: 604800x seconds.\n\n- `ddays(x = 1)`: 86400x seconds.\n\n- `dhours(x = 1)`: 3600x seconds.\n\n- `dminutes(x = 1)`: 60x seconds.\n\n- `dseconds(x = 1)`: x seconds.\n\n- `dmilliseconds(x = 1)`: x \\* 10^-3^ seconds.\n\n- `dmicroseconds(x = 1)`: x \\* 10^-6^ seconds.\n\n- `dnanoseconds(x = 1)`: x \\* 10^-9^ seconds.\n\n- `dpicoseconds(x = 1)`: x \\* 10^-12^ seconds.\n\n- `duration(num = NULL, units = \"second\", ...)`: An automation friendly duration constructor.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n duration(5, unit = \"years\")\n ```\n :::\n\n\n- `as.duration(x, ...)`: Coerce a timespan to a duration.\n Also `is.duration()`, `is.difftime()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n as.duration(p)\n ```\n :::\n\n\n- `make_difftime(x)`: Make diffime with the specified number of units.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n make_difftime(99999)\n ```\n :::\n\n\n### Intervals\n\nDivide an interval by a duration to determine its physical length, divide by an interval by a period to determine its implied length in clock time.\n\nMake an interval with `interval()` or `%--%`, e.g.\n\n\n::: {.cell}\n\n```{.r .cell-code}\ni <- interval(ymd(\"2017-01-01\"), d)\ni\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 2017-01-01 UTC--2017-11-01 UTC\n```\n:::\n\n```{.r .cell-code}\n# Shows the exact length in seconds, and the equivalent in common units\nj <- d %--% ymd(\"2017-12-31\")\nj\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] 2017-11-01 UTC--2017-12-31 UTC\n```\n:::\n:::\n\n\n- `a %within% b`: Does interval or dte0time `a` fall within interval `b`?\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n now() %within% i\n ```\n :::\n\n\n- `int_start(int)`: Access/set the start date-time of an interval.\n Also `int_end()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n int_start(i) <- now()\n int_start(i)\n ```\n :::\n\n\n- `int_aligns(int1, int2)`: Do two intervals share a boundary?\n Also `int_overlaps()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n int_aligns(i, j)\n ```\n :::\n\n\n- `int_diff(times)`: Make the intervals that occur between the date-times in a vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n v <- c(dt, dt + 100, dt + 1000)\n int_diff(v)\n ```\n :::\n\n\n- `int_flip(int)`: Reverse the direction of an interval.\n Also `int_standardize()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n int_flip(i)\n ```\n :::\n\n\n- `int_length(int)`: Length in seconds.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n int_length(i)\n ```\n :::\n\n\n- `int_shift(int, by)`: Shifts an interval up or down the timeline by a timespan.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n int_shift(i, days(-1))\n ```\n :::\n\n\n- `as.interval(x, start, ...)`: Coerce a timespan to an interval with the start date-time.\n Also `is.interval()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n as.interval(days(-1), start = now())\n ```\n :::\n\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [lubridate.tidyverse.org](https://lubridate.tidyverse.org).\n\nUpdated: 2023-06.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"lubridate\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.9.2'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", "supporting": [], "filters": [ "rmarkdown/pagebreak.lua" diff --git a/_freeze/html/package-development/execute-results/html.json b/_freeze/html/package-development/execute-results/html.json index fdcb21d3..d8b72de0 100644 --- a/_freeze/html/package-development/execute-results/html.json +++ b/_freeze/html/package-development/execute-results/html.json @@ -1,7 +1,7 @@ { - "hash": "4e9c8c48d29c4ed20b22619428b812b2", + "hash": "e54b41f8a8d238ee224470a1772f4ed5", "result": { - "markdown": "---\ntitle: \"Package Development :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: true\n---\n\n::: {.cell .column-margin}\n\"\"\n

\n

Download PDF

\n\n
\n

Translations (PDF)

\n* Dutch\n* German\n* Italian\n* Korean\n* Spanish\n* Vietnamese\n:::\n\n```{=html}\n\n```\n\nVisit [r-pkgs.org](https://r-pkgs.org) to learn more about writing and publishing packages for R.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(devtools)\nlibrary(testthat)\nlibrary(roxygen2)\n```\n:::\n\n\n## Package Structure\n\nA package is a convention for organizing files into directories, and creates a shareable, installable collection of functions, sample data, and documentation.\nThis cheatsheet shows you how to work with the 7 most common parts of an R package:\n\n- R/: Write R code for your package\n- DESCRIPTION: Set up metadata and organize package functions\n- NAMESPACE\n- tests/: Verify your code is correct\n- man/\n- vignettes/: Document your code and write tutorials and how-tos\n- data/: Include data sets in your package\n\nThere are multiple packages useful to package development, including `usethis` which handily automates many of the more repetitive tasks.\nLoad and install `devtools` which wraps together several of these packages to access everything in one step.\n\n## Getting Started\n\nOnce per machine:\n\n- Get set up with `use_r_profile()` so devtools is always loaded in interactive R sessions.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n if (interactive()) {\n require(\"devtools\", quietly = TRUE)\n # automatically attaches usethis\n }\n ```\n :::\n\n\n- `create_github_token()`: Set up GitHub credentials.\n\n- `git_vaccinate()`: Ignores common special files.\n\nOnce per package:\n\n- `create_package()`: Create a project with package scaffolding.\n\n- `use_git()`: Activate git.\n\n- `use_github()`: Connect to GitHub.\n\n- `use_github_action()`: Set up automated package checks.\n\nHaving problems with git?\nGet a situation report with `git_sitrep()`.\n\n## Workflow\n\n\n```{=html}\n\n\n\n```\n\n### Key steps in the workflow (with keyboard shortcuts)\n\n- **`load_all()`** (Ctrl/Cmd + Shift + L): Load code\n- **`test()`** (Ctrl/Cmd + Shift + T): Run tests\n- **`document()`** (Ctrl/Cmd + Shift + D): Rebuild docs and NAMESPACE\n- **`check()`** (Ctrl/Cmd + Shift + E): Check complete package\n\n## R/\n\nAll of the R code in your package goes in `R/`.\nA package with just an `R/` directory is still a very useful package.\n\n- Create a new package project with `create_package(\"path/to/name\")`.\n\n- Create R files with `use_r(\"file-name\")`.\n\n- Follow the tidyverse style guide at [style.tidyverse.org](style.tidyverse.org \"Tidyverse style guide\")\n\n- Put your cursor on a function and press `F2` to go to its definition\n\n- Find a function or file with the keyboard shortcut `Ctrl+.`\n\n## DESCRIPTION\n\nThe DESCRIPTION file describes your package, sets up how your package will work with other packages, and applies a license.\n\n- Pick a license with `use_mit_license()`, `use_gpl3_license()`, `use_proprietary_license()`.\n\n- Add packages that you need with `use_package()`.\n\n**Import** packages that your package requires to work.\nR will install them when it installs your package.\nAdd with `use_package(pkgname, type = \"imports\")`\n\n**Suggest** packages that developers of your package need.\nUsers can install or not, as they like.\nAdd with `use_package(pkgname, type = \"suggests\")`\n\n## NAMESPACE\n\nThe `NAMESPACE` file helps you make your packages self-contained: it won't interfere with other packages, and other packages won't interfere with it.\n\n- Export functions for users by placing `@export` in their roxygen comments.\n\n- Use objects from other packages with `package::object` or `@importFrom package object` (recommended) or `@import package` (use with caution).\n\n- Call `document()` to generate `NAMESPACE` and `load_all()` to reload.\n\n| DESCRIPTION | NAMESPACE |\n|------------------------------|---------------------------------|\n| Makes **packages** available | Makes **functions** available |\n| Mandatory | Optional (can use `::` instead) |\n| `use_package()` | `use_import_from()` |\n\n: Table comparing features/purpose of DESCRIPTION (left column) vs NAMESPACE (right column)\n\n\n\n## man/\n\nThe documentation will become the help pages in your package.\n\n- Document each function with a roxygen block above its definition in R/.\n In RStudio, **Code \\> Insert Roxygen Skeleton** (Keyboard shortcut: Mac `Shift+Option+Cmd+R`, Windows/Linux `Shift+Alt+Ctrl+R`) helps.\n\n- Document each data set with an roxygen block above the name of the data set in quotes.\n\n- Document the package with `use_package_doc()`.\n\n- Build documentation in man/ from Roxygen blocks with `document()`.\n\n### roxygen2\n\nThe **roxygen2** package lets you write documentation inline in your .R files with shorthand syntax.\n\n- Add roxygen documentation as comments beginning with `#'`.\n\n- Place an roxygen `@` tag (right) after `#'` to supply a specific section of documentation.\n\n- Untagged paragraphs will be used to generate a title, description, and details section (in that order).\n\n\n::: {.cell}\n\n```{.r .cell-code}\n#' Add together two numbers\n#' \n#' @param x A number.\n#' @param y A number.\n#' @returns The sum of `x` and `y`\n#' @export\n#' @examples\n#' add(1, 1)\nadd <- function(x, y) {\n x + y\n}\n```\n:::\n\n\n#### Common roxygen Tags:\n\n- `@examples`\n- `@export`\n- `@param`\n- `@returns`\n\nAlso:\n\n- `@description`\n- `@examplesif`\n- `@family`\n- `@inheritParams`\n- `@rdname`\n- `@seealso`\n\n## vignettes/\n\n- Create a vignette that is included with your package with `use_vignette()`.\n- Create an article that only appears on the website with `use_article()`.\n- Write the body of your vignettes in R Markdown.\n\n## Websites with pkgdown\n\n- Use GitHub and `use_pkgdown_github_pages()` to set up pkgdown and configure an automated workflow using GitHub Actions and Pages.\n- If you're not using GitHub, call `use_pkgdown()` to configure pkgdown. Then build locally with `pkgdown::build_site()`.\n\n## README.Rmd + NEWS.md\n\n- Create a README and NEWS markdown files with `use_readme_rmd()` and `use_news_md()`.\n\n## tests/\n\n- Create a test file with `use_test()`.\n- Write tests with `test_that()` and `expect_()`.\n- Run all tests with `test()` and run tests for current file with `test_active_file()`.\n- See coverage of all files with `test_coverage()` and see coverage of current file with `test_coverage_active_file()`.\n\n| Expect statement | Tests |\n|---------------------|----------------------------------------|\n| `expect_equal()` | Is equal? (within numerical tolerance) |\n| `expect_error()` | Throws specified error? |\n| `expect_snapshot()` | Output is unchanged? |\n\n: Table of expect functions and what each one tests\n\n\n::: {.cell}\n\n```{.r .cell-code}\ntest_that(\"Math works\", {\n expect_equal(1 + 1, 2)\n expect_equal(1 + 2, 3)\n expect_equal(1 + 3, 4)\n})\n```\n:::\n\n\n## data/\n\n- Record how a data set was prepared as an R script and save that script to `data-raw/` with `use_data_raw()`.\n- Save a prepared data object to `data/` with `use_data()`.\n\n## Package States\n\nThe contents of a package can be stored on disk as a:\n\n- **source** - a directory with sub-directories (as shown in Package Structure)\n- **bundle** - a single compressed file (.tar.gz)\n- **binary** - a single compressed file optimized for a specific OS\n\nPackages exist in those states locally or remotely, e.g. on CRAN or on GitHub.\n\nFrom those states, a package can be installed into an R **library** and then loaded into **memory** for use during an R session.\n\n\n::: {.cell}\n::: {.cell-output-display}\n![](images/install-load.png){fig-alt='A diagram describing the functions that move a package between different states. The description below describes this in detail.\n' width=1013}\n:::\n:::\n\n\n\n\nUse the functions below to move between these states:\n\n- `library()`: Installed in Library to loaded in Memory.\n- `install.packages()`: Binary from CRAN repository to installed in Library.\n- `install.packages(type = \"source\")`: Source code from CRAN repository to Bundle, to installed in Library.\n- `install_github()`: Source code from GitHub repository to Bundle to installed in Library.\n- `install()`: Local source code to bundle to installed in Library.\n- `build()`: Local source to Bundle.\n- `build(binary = TRUE)`: Local source to Binary.\n- `load_all()`: Local source to loaded in Memory.\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [r-pkgs.org](https://r-pkgs.org).\n\nUpdated: 2023-05.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"devtools\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '2.4.5'\n```\n:::\n\n```{.r .cell-code}\npackageVersion(\"usethis\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '2.1.6.9000'\n```\n:::\n\n```{.r .cell-code}\npackageVersion(\"testthat\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '3.1.8'\n```\n:::\n\n```{.r .cell-code}\npackageVersion(\"roxygen2\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '7.2.3'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", + "markdown": "---\ntitle: \"Package Development :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: true\n---\n\n::: {.cell .column-margin}\n\"Hex\n

\n

Download PDF

\n\"\"/\n
\n

Translations (PDF)

\n* Dutch\n* German\n* Italian\n* Korean\n* Spanish\n* Vietnamese\n:::\n\n```{=html}\n\n```\n\nVisit [r-pkgs.org](https://r-pkgs.org) to learn more about writing and publishing packages for R.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(devtools)\nlibrary(testthat)\nlibrary(roxygen2)\n```\n:::\n\n\n## Package Structure\n\nA package is a convention for organizing files into directories, and creates a shareable, installable collection of functions, sample data, and documentation.\nThis cheatsheet shows you how to work with the 7 most common parts of an R package:\n\n- R/: Write R code for your package\n- DESCRIPTION: Set up metadata and organize package functions\n- NAMESPACE\n- tests/: Verify your code is correct\n- man/\n- vignettes/: Document your code and write tutorials and how-tos\n- data/: Include data sets in your package\n\nThere are multiple packages useful to package development, including `usethis` which handily automates many of the more repetitive tasks.\nLoad and install `devtools` which wraps together several of these packages to access everything in one step.\n\n## Getting Started\n\nOnce per machine:\n\n- Get set up with `use_r_profile()` so devtools is always loaded in interactive R sessions.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n if (interactive()) {\n require(\"devtools\", quietly = TRUE)\n # automatically attaches usethis\n }\n ```\n :::\n\n\n- `create_github_token()`: Set up GitHub credentials.\n\n- `git_vaccinate()`: Ignores common special files.\n\nOnce per package:\n\n- `create_package()`: Create a project with package scaffolding.\n\n- `use_git()`: Activate git.\n\n- `use_github()`: Connect to GitHub.\n\n- `use_github_action()`: Set up automated package checks.\n\nHaving problems with git?\nGet a situation report with `git_sitrep()`.\n\n## Workflow\n\n\n```{=html}\n\n\n\n```\n\n### Key steps in the workflow (with keyboard shortcuts)\n\n- **`load_all()`** (Ctrl/Cmd + Shift + L): Load code\n- **`test()`** (Ctrl/Cmd + Shift + T): Run tests\n- **`document()`** (Ctrl/Cmd + Shift + D): Rebuild docs and NAMESPACE\n- **`check()`** (Ctrl/Cmd + Shift + E): Check complete package\n\n## R/\n\nAll of the R code in your package goes in `R/`.\nA package with just an `R/` directory is still a very useful package.\n\n- Create a new package project with `create_package(\"path/to/name\")`.\n\n- Create R files with `use_r(\"file-name\")`.\n\n- Follow the tidyverse style guide at [style.tidyverse.org](style.tidyverse.org \"Tidyverse style guide\")\n\n- Put your cursor on a function and press `F2` to go to its definition\n\n- Find a function or file with the keyboard shortcut `Ctrl+.`\n\n## DESCRIPTION\n\nThe DESCRIPTION file describes your package, sets up how your package will work with other packages, and applies a license.\n\n- Pick a license with `use_mit_license()`, `use_gpl3_license()`, `use_proprietary_license()`.\n\n- Add packages that you need with `use_package()`.\n\n**Import** packages that your package requires to work.\nR will install them when it installs your package.\nAdd with `use_package(pkgname, type = \"imports\")`\n\n**Suggest** packages that developers of your package need.\nUsers can install or not, as they like.\nAdd with `use_package(pkgname, type = \"suggests\")`\n\n## NAMESPACE\n\nThe `NAMESPACE` file helps you make your packages self-contained: it won't interfere with other packages, and other packages won't interfere with it.\n\n- Export functions for users by placing `@export` in their roxygen comments.\n\n- Use objects from other packages with `package::object` or `@importFrom package object` (recommended) or `@import package` (use with caution).\n\n- Call `document()` to generate `NAMESPACE` and `load_all()` to reload.\n\n| DESCRIPTION | NAMESPACE |\n|------------------------------|---------------------------------|\n| Makes **packages** available | Makes **functions** available |\n| Mandatory | Optional (can use `::` instead) |\n| `use_package()` | `use_import_from()` |\n\n: Table comparing features/purpose of DESCRIPTION (left column) vs NAMESPACE (right column)\n\n\n\n## man/\n\nThe documentation will become the help pages in your package.\n\n- Document each function with a roxygen block above its definition in R/.\n In RStudio, **Code \\> Insert Roxygen Skeleton** (Keyboard shortcut: Mac `Shift+Option+Cmd+R`, Windows/Linux `Shift+Alt+Ctrl+R`) helps.\n\n- Document each data set with an roxygen block above the name of the data set in quotes.\n\n- Document the package with `use_package_doc()`.\n\n- Build documentation in man/ from Roxygen blocks with `document()`.\n\n### roxygen2\n\nThe **roxygen2** package lets you write documentation inline in your .R files with shorthand syntax.\n\n- Add roxygen documentation as comments beginning with `#'`.\n\n- Place an roxygen `@` tag (right) after `#'` to supply a specific section of documentation.\n\n- Untagged paragraphs will be used to generate a title, description, and details section (in that order).\n\n\n::: {.cell}\n\n```{.r .cell-code}\n#' Add together two numbers\n#' \n#' @param x A number.\n#' @param y A number.\n#' @returns The sum of `x` and `y`\n#' @export\n#' @examples\n#' add(1, 1)\nadd <- function(x, y) {\n x + y\n}\n```\n:::\n\n\n#### Common roxygen Tags:\n\n- `@examples`\n- `@export`\n- `@param`\n- `@returns`\n\nAlso:\n\n- `@description`\n- `@examplesif`\n- `@family`\n- `@inheritParams`\n- `@rdname`\n- `@seealso`\n\n## vignettes/\n\n- Create a vignette that is included with your package with `use_vignette()`.\n- Create an article that only appears on the website with `use_article()`.\n- Write the body of your vignettes in R Markdown.\n\n## Websites with pkgdown\n\n- Use GitHub and `use_pkgdown_github_pages()` to set up pkgdown and configure an automated workflow using GitHub Actions and Pages.\n- If you're not using GitHub, call `use_pkgdown()` to configure pkgdown. Then build locally with `pkgdown::build_site()`.\n\n## README.Rmd + NEWS.md\n\n- Create a README and NEWS markdown files with `use_readme_rmd()` and `use_news_md()`.\n\n## tests/\n\n- Create a test file with `use_test()`.\n- Write tests with `test_that()` and `expect_()`.\n- Run all tests with `test()` and run tests for current file with `test_active_file()`.\n- See coverage of all files with `test_coverage()` and see coverage of current file with `test_coverage_active_file()`.\n\n| Expect statement | Tests |\n|---------------------|----------------------------------------|\n| `expect_equal()` | Is equal? (within numerical tolerance) |\n| `expect_error()` | Throws specified error? |\n| `expect_snapshot()` | Output is unchanged? |\n\n: Table of expect functions and what each one tests\n\n\n::: {.cell}\n\n```{.r .cell-code}\ntest_that(\"Math works\", {\n expect_equal(1 + 1, 2)\n expect_equal(1 + 2, 3)\n expect_equal(1 + 3, 4)\n})\n```\n:::\n\n\n## data/\n\n- Record how a data set was prepared as an R script and save that script to `data-raw/` with `use_data_raw()`.\n- Save a prepared data object to `data/` with `use_data()`.\n\n## Package States\n\nThe contents of a package can be stored on disk as a:\n\n- **source** - a directory with sub-directories (as shown in Package Structure)\n- **bundle** - a single compressed file (.tar.gz)\n- **binary** - a single compressed file optimized for a specific OS\n\nPackages exist in those states locally or remotely, e.g. on CRAN or on GitHub.\n\nFrom those states, a package can be installed into an R **library** and then loaded into **memory** for use during an R session.\n\n\n::: {.cell}\n::: {.cell-output-display}\n![](images/install-load.png){fig-alt='A diagram describing the functions that move a package between different states. The description below describes this in detail.\n' width=1013}\n:::\n:::\n\n\n\n\nUse the functions below to move between these states:\n\n- `library()`: Installed in Library to loaded in Memory.\n- `install.packages()`: Binary from CRAN repository to installed in Library.\n- `install.packages(type = \"source\")`: Source code from CRAN repository to Bundle, to installed in Library.\n- `install_github()`: Source code from GitHub repository to Bundle to installed in Library.\n- `install()`: Local source code to bundle to installed in Library.\n- `build()`: Local source to Bundle.\n- `build(binary = TRUE)`: Local source to Binary.\n- `load_all()`: Local source to loaded in Memory.\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [r-pkgs.org](https://r-pkgs.org).\n\nUpdated: 2023-06.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"devtools\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '2.4.5'\n```\n:::\n\n```{.r .cell-code}\npackageVersion(\"usethis\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '2.1.6.9000'\n```\n:::\n\n```{.r .cell-code}\npackageVersion(\"testthat\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '3.1.8'\n```\n:::\n\n```{.r .cell-code}\npackageVersion(\"roxygen2\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '7.2.3'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", "supporting": [], "filters": [ "rmarkdown/pagebreak.lua" diff --git a/_freeze/html/plumber/execute-results/html.json b/_freeze/html/plumber/execute-results/html.json index bc09d90a..e456872e 100644 --- a/_freeze/html/plumber/execute-results/html.json +++ b/_freeze/html/plumber/execute-results/html.json @@ -1,7 +1,7 @@ { - "hash": "cdf96a9f244ec9e9a7ee45bdad77a8d5", + "hash": "46b6a812ccb109d061b0f154650f10eb", "result": { - "markdown": "---\ntitle: \"REST APIs with plumber :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: false\n---\n\n::: {.cell .column-margin}\n\"\"\n

\n

Download PDF

\n\n
\n

\n:::\n\n\n## Introduction to REST APIs\n\nWeb APIs use **HTTP** to communcation between **client** and **server**.\n\n### HTTP\n\nHTTP is built around a **request** and a **response**.\nA **client** makes a request to a **server**, which handles the request and provides a response.\nRequests and responses are specially formatted text containing details and data about the exchange between client and server.\n\n### Request\n\n`GET / get HTTP/1.1` -\\> HTTP Method, Path, HTTP Version\n\n`Host:`, `User-Agent:`, `Accept:` -\\> Headers\n\n`Request Body` -\\> Message body\n\n```\ncurl -v \"http://httpbin.org/get\"\n\n#> GET / get HTTP/1.1\n#> Host: httpbin.org\n#> User-Agent: curl/7.55.1\n#> Accept: */*\n#\n# Request Body\n```\n\n### Response\n\n`HTTP/1.1 200 OK` -\\> HTTP Version, Status code, Reason phrase\n\n`Connection:`, `Date:` -\\> Headers\n\n`Response Body` -\\> Message body\n\n\n::: {.cell}\n\n```{.r .cell-code}\n#< HTTP/1.1 200 OK\n#< Connection: keep-alive\n#< Date: Thu, 02 Aug 2018 18:22:22 GMT\n#\n# Response Body\n```\n:::\n\n\n## Plumber: Build APIs with R\n\nPlumber uses special comments to turn any arbitrary R code into API endpoints.\nThe example below defines a function that takes the `msg` argument and returns it embedded in additional text.\n\nPlumber comments begin with `#*` and `@` decoators define API characteristics.\nIn HTTP methods such as `@get` the `/` defines the location of the endpoint.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(plumber)\n\n#* @apiTitle Plumber Example API\n\n#* Echo back the input\n#* @param msg The message to echo\n#* @get /echo\nfunction(msg = \"\") {\n list(\n msg = paste0(\"The message is: '\", msg, \"'\")\n )\n}\n```\n:::\n\n\n## Plumber piperline\n\nPlumber endpoints contain R code that is executed in response to an HTTP request.\nIncoming requests pass through a set of mechanisms before a response is returned to the client.\n\n- Filters: Filters can forward requests (after potentially mutating them), throw errors, or return a response without forwarding the request.\n Filters are defined similarly to endpoints using the `@filter [name]` tag.\n By default, filters apply to all endpoints.\n Endpoints can opt out of filters using the `@preempt` tag.\n\n- Parsers: Parsers determine how Plumber parses the incoming request body.\n By default Plumber parses the request body as JavaScript Object Notation (JSON).\n Other parsers, including custom parsers, are identified using the `@parser [parser name]` tag.\n All registered parsers can be viewed with `registered_parsers()`.\n\n- Endpoint: Endpoints define the R code that is executed in response to incoming requests.\n These endpoints correspond to HTTP methods and respond to incoming requests that match the defined method.\n\n - Methods\n\n - `@get` - request a resource\n - `@post` - send data in body\n - `@put` - store/update data\n - `@delete` - delete resource\n - `@head` - no request body\n - `@options` - describe options\n - `@patch` - partial changes\n - `@use` - use all methods\n\n- Serializer: Serializers determine how Plumber returns results to the client.\n By default Plumber serializes the R object returned into JavaScript Object Notation (JSON).\n Other serializers, including custom serializers, are identified using the `@serializer [serializer name]` tag.\n All registered serializers can be viewed with `registered_serializers()`.\n\nIdentify as filter with `@filter`, filter name is `log`, and forward request with `forward()`:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(plumber)\n\n#* @filter log\nfunction(req, res) {\n print(req$HTTP_USER_AGENT)\n forward()\n}\n```\n:::\n\n\nDefine the endpoint description, opt out of the log filter, define the parser, HTTP method and endpoint path, and serializer:\n\n\n::: {.cell}\n\n```{.r .cell-code}\n#* Convert request body to uppercase\n#* @prempt log\n#* @parser json\n#* @post /uppercase\n#* @serializer json\nfunction(req, res) {\n toupper(req$body)\n}\n```\n:::\n\n\n## Running Plumber APIs\n\nPlumber APIs can be run programmatically from within an R session.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(plumber)\n\n# Path to API definition\nplumb(\"plumber.R\") |>\n pr_run(port = 5762) # Specify API port\n```\n:::\n\n\nThis runs the API on the host machine supported by the current R session.\n\n### IDE Integration\n\n![](images/plumber-ide.png){fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about plumber features in the RStudio IDE {aria-hidden=\"true\"}\n\n### plumber features in the RStudio IDE\n\n- Create new Plumber API\n- Publish API to RStudio Connect\n- Run API in current R session\n:::\n\n## Documentation\n\nPlumber APIs automatically generate an OpenAPI specification file.\nThis specification file can be interpreted to generate a dynamic user-interface for the API.\nThe default interface is generated via Swagger\n\n![](images/plumber-documentation.png){fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the Swagger user interface\n\n### Features in the Swagger user interface\n\n- Endpoint details\n- Parameter details\n- Edit parameters\n- Send request\n- curl command used to send request\n:::\n\n## Interact with the API\n\nOnce the API is running, it can be interacted with using any HTTP client.\nNote that using `httr` requires using a separate R session from the one serving the API.\n\n\n::: {.cell}\n\n```{.r .cell-code}\n(resp <- httr::GET(\"localhost:5762/echo?msg=Hello\")) \n#> Response [http://localhost:5762/echo?msg=Hello] \n#> #> Date: 2018-08-07 20:06\n#> Status: 200\n#> Content-Type: application/json\n#> Size: 35 B\nhttr::content(resp, as = \"text\")\n#> [1] \"{\\\"msg\\\":[\\\"The message is: 'Hello'\\\"]}\"\n```\n:::\n\n\n\n\n## Programmatic Plumber\n\n### Tidy Plumber\n\nPlumber is exceptionally customizable.\nIn addition to using special comments to create APIs, APIs can be created entirely programatically.\nThis exposes additional features and functionality.\nPlumber has a convenient \"tidy\" interface that allows API routers to be built piece by piece.\nThe following example is part of a standard `plumber.R` file.\n\nUse the `@plumber` tag, create a function that accepts and modifies a plumber router (`pr`), and use \"tidy functions\" like `pr_get()` and `pr_post()` for buildings out Plumber API.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(plumber)\n\n#* @plumber\nfunction(pr) {\n pr |>\n pr_get(path = \"/echo\",\n handler = function(msg = \"\") {\n list(msg = paste0(\n \"The message is: '\",\n msg,\n \"'\")\n )\n }) |>\n pr_get(path = \"/plot\",\n handler = function() {\n rand <- rnorm(100)\n hist(rand)\n },\n serializer = serializer_png()) |>\n pr_post(path = \"/sum\",\n handler = function(a, b) {\n as.numeric(a) + as.numeric(b)\n })\n}\n```\n:::\n\n\n### OpenAPI\n\nPlumber automatically creates an OpenAPI specification file based on Plumber componenets.\nThis file can be further modified using `pr_set_api_spec()` with either a function that modifies the existing specification or a path to a `.yaml` or `.json` specification file.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(plumber)\n\n#* @param msg The message to echo\n#* @get /echo\nfunction(msg = \"\") {\n list(\n msg = paste0(\"The messahe is: '\", msg, \"'\")\n )\n}\n\n#* @plumber\nfunction(pr) {\n pr |>\n pr_set_api_spec(\n function(spec) {\n spec$paths[[\"echo\"]]$get$summary <- \"Echo back the input\"\n spec # Return the updated specification\n }\n )\n}\n```\n:::\n\n\nBy default, Swagger is used to interpret the OpenAPI specification file and generate the user interface for the API.\nOther interpreters can be used to adjust the look and feel of the user interface via `pr_set_docs()`.\n\n## Advanced Plumber\n\n### Request and Response\n\nPlumber provides access to special `req` and `res` objects that can be passed to Plumber functions.\nThese objects provide access to the request submitted by the client and the response that will be sent to the client.\nEach object has several components, the most helpful of which are outlined below:\n\n**Request Objects**\n\n| Name | Example | Description |\n|-------------------|-------------------|----------------------------------|\n| `req$pr` | `plumber::pr()` | The Plumber router processing the request |\n| `req$body` | `list(a = 1)` | Typically the same as `argsBody` |\n| `req$argsBody` | `list(a = 1)` | The parsed body output |\n| `req$argsPath` | `list(c = 3)` | The values of the path arguments |\n| `req$argsQuery` | `list(e = 5)` | The parsed output from `req$QUERY_STRING` |\n| `req$cookies` | `list(cook = \"a\")` | A list of cookies |\n| `req$REQUEST_METHOD` | `\"GET\"` | The method used for the HTTP request |\n| `req$PATH_INFO` | `\"/\"` | The path of the incoming HTTP request |\n| `req$HTTP_*` | `\"HTTP_USER_AGENT\"` | All of the HTTP headers sent with the request |\n| `req$bodyRaw` | `charToRaw(\"a = 1\")` | The `raw()` contents of the request body |\n\n: Table of request object names, examples, and descriptions\n\n**Response Objects**\n\n| Name | Example | Description |\n|-------------------|----------------------|-------------------------------|\n| `res$headers` | `list(header = \"abc\")` | HTTP headers to include in the response |\n| `res$setHeader()` | `setHeader(\"foo\", \"bar\")` | Sets an HTTP header |\n| `res$setCookie()` | `setCookie(\"foo\", \"bar\")` | Sets an HTTP cookie on the client |\n| `res$removeCookie()` | `removeCookie(\"foo\")` | Removes an HTTP cooki4 |\n| `res$body` | `\"{\\\"a\\\":[1]}\"` | Serialized output |\n| `res$status` | `200` | The response HTTP status code |\n| `res$toResponse()` | `toResponse()` | A list of `status`, `headers`, and `body` |\n\n: Table of response object names, examples, and descriptions\n\n### Async Plumber\n\nPlumber supports asynchronous execution via the **future** R package.\nThis pattern allows Plumber to concurrently process multiple requests.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(plumber)\n\n# Set the execution plan\nfuture::plan(\"multisession\")\n\n#* @get /slow\nfunction() {\n promises::future_promise({\n slow_calc() # Slow calculation\n })\n}\n```\n:::\n\n\n### Mounting Routers\n\nPlumber routers can be combined by mounting routers into other routers.\nThis can be beneficial when building routers that involve several different endpoints and you want to break each component out into a separate router.\nThese separate routers can even be separate files loaded using `plumb()`.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(plumber)\n\n# Create an initial router\nroute <- pr() |>\n pr_get(\"/foo\", function() \"foo\")\n\n#* @plumber\nfunction(pr) {\n pr |>\n pr_mount(\"/bar\", route)\n}\n```\n:::\n\n\nIn the above example, the final route is `/bar/foo`.\n\n### Running Examples\n\nSome packages, like the Plumber package itself, may include example Plumber APIs.\nAvailable APIs can be viewed using `available_apis()`.\nThese example APIs can be run with `plumb_api()` combined with `pr_run()`.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(plumber)\n\nplumb_api(package = \"plumber\", # package name\n name = \"01-append\", # API name\n edit = TRUE) |> # optionally open the file for editing\n pr_run() # run the example API\n```\n:::\n\n\n## Deploying Plumber APIs\n\nOnce Plumber APIs have been developed, they often need to be deployed somewhere to be useful.\nPlumber APIs can be deployed in a variety of different ways.\nOne of the easiest way to deploy Plumber APIs is using RStudio Connect, which supports push button publishing from the RStudio IDE.\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [rplumber.io](https://www.rplumber.io/).\n\nUpdated: 2023-05.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"plumber\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.2.1'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", + "markdown": "---\ntitle: \"REST APIs with plumber :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: false\n---\n\n::: {.cell .column-margin}\n\"Hex\n

\n

Download PDF

\n\"\"/\n
\n

\n:::\n\n\n## Introduction to REST APIs\n\nWeb APIs use **HTTP** to communcation between **client** and **server**.\n\n### HTTP\n\nHTTP is built around a **request** and a **response**.\nA **client** makes a request to a **server**, which handles the request and provides a response.\nRequests and responses are specially formatted text containing details and data about the exchange between client and server.\n\n### Request\n\n`GET / get HTTP/1.1` -\\> HTTP Method, Path, HTTP Version\n\n`Host:`, `User-Agent:`, `Accept:` -\\> Headers\n\n`Request Body` -\\> Message body\n\n``` \ncurl -v \"http://httpbin.org/get\"\n\n#> GET / get HTTP/1.1\n#> Host: httpbin.org\n#> User-Agent: curl/7.55.1\n#> Accept: */*\n#\n# Request Body\n```\n\n### Response\n\n`HTTP/1.1 200 OK` -\\> HTTP Version, Status code, Reason phrase\n\n`Connection:`, `Date:` -\\> Headers\n\n`Response Body` -\\> Message body\n\n\n::: {.cell}\n\n```{.r .cell-code}\n#< HTTP/1.1 200 OK\n#< Connection: keep-alive\n#< Date: Thu, 02 Aug 2018 18:22:22 GMT\n#\n# Response Body\n```\n:::\n\n\n## Plumber: Build APIs with R\n\nPlumber uses special comments to turn any arbitrary R code into API endpoints.\nThe example below defines a function that takes the `msg` argument and returns it embedded in additional text.\n\nPlumber comments begin with `#*` and `@` decoators define API characteristics.\nIn HTTP methods such as `@get` the `/` defines the location of the endpoint.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(plumber)\n\n#* @apiTitle Plumber Example API\n\n#* Echo back the input\n#* @param msg The message to echo\n#* @get /echo\nfunction(msg = \"\") {\n list(\n msg = paste0(\"The message is: '\", msg, \"'\")\n )\n}\n```\n:::\n\n\n## Plumber piperline\n\nPlumber endpoints contain R code that is executed in response to an HTTP request.\nIncoming requests pass through a set of mechanisms before a response is returned to the client.\n\n- Filters: Filters can forward requests (after potentially mutating them), throw errors, or return a response without forwarding the request.\n Filters are defined similarly to endpoints using the `@filter [name]` tag.\n By default, filters apply to all endpoints.\n Endpoints can opt out of filters using the `@preempt` tag.\n\n- Parsers: Parsers determine how Plumber parses the incoming request body.\n By default Plumber parses the request body as JavaScript Object Notation (JSON).\n Other parsers, including custom parsers, are identified using the `@parser [parser name]` tag.\n All registered parsers can be viewed with `registered_parsers()`.\n\n- Endpoint: Endpoints define the R code that is executed in response to incoming requests.\n These endpoints correspond to HTTP methods and respond to incoming requests that match the defined method.\n\n - Methods\n\n - `@get` - request a resource\n - `@post` - send data in body\n - `@put` - store/update data\n - `@delete` - delete resource\n - `@head` - no request body\n - `@options` - describe options\n - `@patch` - partial changes\n - `@use` - use all methods\n\n- Serializer: Serializers determine how Plumber returns results to the client.\n By default Plumber serializes the R object returned into JavaScript Object Notation (JSON).\n Other serializers, including custom serializers, are identified using the `@serializer [serializer name]` tag.\n All registered serializers can be viewed with `registered_serializers()`.\n\nIdentify as filter with `@filter`, filter name is `log`, and forward request with `forward()`:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(plumber)\n\n#* @filter log\nfunction(req, res) {\n print(req$HTTP_USER_AGENT)\n forward()\n}\n```\n:::\n\n\nDefine the endpoint description, opt out of the log filter, define the parser, HTTP method and endpoint path, and serializer:\n\n\n::: {.cell}\n\n```{.r .cell-code}\n#* Convert request body to uppercase\n#* @prempt log\n#* @parser json\n#* @post /uppercase\n#* @serializer json\nfunction(req, res) {\n toupper(req$body)\n}\n```\n:::\n\n\n## Running Plumber APIs\n\nPlumber APIs can be run programmatically from within an R session.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(plumber)\n\n# Path to API definition\nplumb(\"plumber.R\") |>\n pr_run(port = 5762) # Specify API port\n```\n:::\n\n\nThis runs the API on the host machine supported by the current R session.\n\n### IDE Integration\n\n![](images/plumber-ide.png){fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about plumber features in the RStudio IDE {aria-hidden=\"true\"}\n\n### plumber features in the RStudio IDE\n\n- Create new Plumber API\n- Publish API to RStudio Connect\n- Run API in current R session\n:::\n\n## Documentation\n\nPlumber APIs automatically generate an OpenAPI specification file.\nThis specification file can be interpreted to generate a dynamic user-interface for the API.\nThe default interface is generated via Swagger\n\n![](images/plumber-documentation.png){fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the Swagger user interface\n\n### Features in the Swagger user interface\n\n- Endpoint details\n- Parameter details\n- Edit parameters\n- Send request\n- curl command used to send request\n:::\n\n## Interact with the API\n\nOnce the API is running, it can be interacted with using any HTTP client.\nNote that using `httr` requires using a separate R session from the one serving the API.\n\n\n::: {.cell}\n\n```{.r .cell-code}\n(resp <- httr::GET(\"localhost:5762/echo?msg=Hello\")) \n#> Response [http://localhost:5762/echo?msg=Hello] \n#> #> Date: 2018-08-07 20:06\n#> Status: 200\n#> Content-Type: application/json\n#> Size: 35 B\nhttr::content(resp, as = \"text\")\n#> [1] \"{\\\"msg\\\":[\\\"The message is: 'Hello'\\\"]}\"\n```\n:::\n\n\n\n\n## Programmatic Plumber\n\n### Tidy Plumber\n\nPlumber is exceptionally customizable.\nIn addition to using special comments to create APIs, APIs can be created entirely programatically.\nThis exposes additional features and functionality.\nPlumber has a convenient \"tidy\" interface that allows API routers to be built piece by piece.\nThe following example is part of a standard `plumber.R` file.\n\nUse the `@plumber` tag, create a function that accepts and modifies a plumber router (`pr`), and use \"tidy functions\" like `pr_get()` and `pr_post()` for buildings out Plumber API.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(plumber)\n\n#* @plumber\nfunction(pr) {\n pr |>\n pr_get(path = \"/echo\",\n handler = function(msg = \"\") {\n list(msg = paste0(\n \"The message is: '\",\n msg,\n \"'\")\n )\n }) |>\n pr_get(path = \"/plot\",\n handler = function() {\n rand <- rnorm(100)\n hist(rand)\n },\n serializer = serializer_png()) |>\n pr_post(path = \"/sum\",\n handler = function(a, b) {\n as.numeric(a) + as.numeric(b)\n })\n}\n```\n:::\n\n\n### OpenAPI\n\nPlumber automatically creates an OpenAPI specification file based on Plumber componenets.\nThis file can be further modified using `pr_set_api_spec()` with either a function that modifies the existing specification or a path to a `.yaml` or `.json` specification file.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(plumber)\n\n#* @param msg The message to echo\n#* @get /echo\nfunction(msg = \"\") {\n list(\n msg = paste0(\"The messahe is: '\", msg, \"'\")\n )\n}\n\n#* @plumber\nfunction(pr) {\n pr |>\n pr_set_api_spec(\n function(spec) {\n spec$paths[[\"echo\"]]$get$summary <- \"Echo back the input\"\n spec # Return the updated specification\n }\n )\n}\n```\n:::\n\n\nBy default, Swagger is used to interpret the OpenAPI specification file and generate the user interface for the API.\nOther interpreters can be used to adjust the look and feel of the user interface via `pr_set_docs()`.\n\n## Advanced Plumber\n\n### Request and Response\n\nPlumber provides access to special `req` and `res` objects that can be passed to Plumber functions.\nThese objects provide access to the request submitted by the client and the response that will be sent to the client.\nEach object has several components, the most helpful of which are outlined below:\n\n**Request Objects**\n\n| Name | Example | Description |\n|-------------------|-------------------|----------------------------------|\n| `req$pr` | `plumber::pr()` | The Plumber router processing the request |\n| `req$body` | `list(a = 1)` | Typically the same as `argsBody` |\n| `req$argsBody` | `list(a = 1)` | The parsed body output |\n| `req$argsPath` | `list(c = 3)` | The values of the path arguments |\n| `req$argsQuery` | `list(e = 5)` | The parsed output from `req$QUERY_STRING` |\n| `req$cookies` | `list(cook = \"a\")` | A list of cookies |\n| `req$REQUEST_METHOD` | `\"GET\"` | The method used for the HTTP request |\n| `req$PATH_INFO` | `\"/\"` | The path of the incoming HTTP request |\n| `req$HTTP_*` | `\"HTTP_USER_AGENT\"` | All of the HTTP headers sent with the request |\n| `req$bodyRaw` | `charToRaw(\"a = 1\")` | The `raw()` contents of the request body |\n\n: Table of request object names, examples, and descriptions\n\n**Response Objects**\n\n| Name | Example | Description |\n|-------------------|----------------------|-------------------------------|\n| `res$headers` | `list(header = \"abc\")` | HTTP headers to include in the response |\n| `res$setHeader()` | `setHeader(\"foo\", \"bar\")` | Sets an HTTP header |\n| `res$setCookie()` | `setCookie(\"foo\", \"bar\")` | Sets an HTTP cookie on the client |\n| `res$removeCookie()` | `removeCookie(\"foo\")` | Removes an HTTP cooki4 |\n| `res$body` | `\"{\\\"a\\\":[1]}\"` | Serialized output |\n| `res$status` | `200` | The response HTTP status code |\n| `res$toResponse()` | `toResponse()` | A list of `status`, `headers`, and `body` |\n\n: Table of response object names, examples, and descriptions\n\n### Async Plumber\n\nPlumber supports asynchronous execution via the **future** R package.\nThis pattern allows Plumber to concurrently process multiple requests.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(plumber)\n\n# Set the execution plan\nfuture::plan(\"multisession\")\n\n#* @get /slow\nfunction() {\n promises::future_promise({\n slow_calc() # Slow calculation\n })\n}\n```\n:::\n\n\n### Mounting Routers\n\nPlumber routers can be combined by mounting routers into other routers.\nThis can be beneficial when building routers that involve several different endpoints and you want to break each component out into a separate router.\nThese separate routers can even be separate files loaded using `plumb()`.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(plumber)\n\n# Create an initial router\nroute <- pr() |>\n pr_get(\"/foo\", function() \"foo\")\n\n#* @plumber\nfunction(pr) {\n pr |>\n pr_mount(\"/bar\", route)\n}\n```\n:::\n\n\nIn the above example, the final route is `/bar/foo`.\n\n### Running Examples\n\nSome packages, like the Plumber package itself, may include example Plumber APIs.\nAvailable APIs can be viewed using `available_apis()`.\nThese example APIs can be run with `plumb_api()` combined with `pr_run()`.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(plumber)\n\nplumb_api(package = \"plumber\", # package name\n name = \"01-append\", # API name\n edit = TRUE) |> # optionally open the file for editing\n pr_run() # run the example API\n```\n:::\n\n\n## Deploying Plumber APIs\n\nOnce Plumber APIs have been developed, they often need to be deployed somewhere to be useful.\nPlumber APIs can be deployed in a variety of different ways.\nOne of the easiest way to deploy Plumber APIs is using RStudio Connect, which supports push button publishing from the RStudio IDE.\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [rplumber.io](https://www.rplumber.io/).\n\nUpdated: 2023-06.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"plumber\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.2.1'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", "supporting": [], "filters": [ "rmarkdown/pagebreak.lua" diff --git a/_freeze/html/purrr/execute-results/html.json b/_freeze/html/purrr/execute-results/html.json index d50af798..ce4ce07c 100644 --- a/_freeze/html/purrr/execute-results/html.json +++ b/_freeze/html/purrr/execute-results/html.json @@ -1,7 +1,7 @@ { - "hash": "ed1f568deea892253ce11d28551d52a4", + "hash": "c956ce10c08d315f49c16c057db3ae7d", "result": { - "markdown": "---\ntitle: \"Apply functions with purrr :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n message: true\n---\n\n::: {.cell .column-margin}\n\"\"\n

\n

Download PDF

\n\n
\n

Translations (PDF)

\n* Korean\n* Russian\n* Spanish\n* Ukrainian\n* Vietnamese\n:::\n\n\npurrr enhances R's functional programming (FP) toolkit by providing a complete and consistent set of tools for working with functions and vectors.\nIf you've never heard of FP before, the best place to start is the family of [`map()`](https://purrr.tidyverse.org/reference/map.html) functions which allow you to replace many for loops with code that is both more succinct and easier to read.\nThe best place to learn about the [`map()`](https://purrr.tidyverse.org/reference/map.html) functions is the [iteration chapter](https://r4ds.had.co.nz/iteration.html) in R for Data Science.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(purrr)\n```\n:::\n\n\n\n\n## Map Functions\n\n### One List\n\n- `map(.x, .f, ...)`: Apply a function to each element of a list of vector, and return a list.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n x <- list(a = 1:10, b = 11:20, c = 21:30)\n l1 <- list(x = c(\"a\", \"b\"), y = c(\"c\", \"d\"))\n map(l1, sort, decreasing = TRUE)\n ```\n :::\n\n\n- `map_dbl(.x, .f, ...)`: Return a double vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map_dbl(x, mean)\n ```\n :::\n\n\n- `map_int(.x, .f, ...)`: Return an integral vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map_int(x, length)\n ```\n :::\n\n\n- `map_chr(.x, .f, ...)`: Return a character vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map_chr(l1, paste, collapse = \"\")\n ```\n :::\n\n\n- `map_lgl(.x, .f, ...)`: Return a logical vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map_lgl(x, is.integer)\n ```\n :::\n\n\n- `map_dfc(.x, .f, ...)`: Return a data frame created by column-binding.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map_dfc(l1, rep, 3)\n ```\n :::\n\n\n- `map_dfr(.x, .f, ...)`: Return a data frame created by row-binding.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map_dfr(x, summary)\n ```\n :::\n\n\n- `walk(.x, .f, ...)`: Trigger side effects, return invisibly.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n walk(x, print)\n ```\n :::\n\n\n### Two Lists\n\n- `map2(.x, .y, .f, ...)`: Apply a function pairs of elements from two lists or vectors, return a list.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n y <- list(1, 2, 3)\n z <- list(4, 5, 6)\n l2 <- list(x = \"a\", y = \"z\")\n map2(x, y, ~ .x * .y)\n ```\n :::\n\n\n- `map2_dbl(.x, .y, .f, ...)`: Return a double vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map2_dbl(y, z, ~ .x / .y)\n ```\n :::\n\n\n- `map2_int(.x, .y, .f, ...)`: Return an integral vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map2_int(y, z, `+`)\n ```\n :::\n\n\n- `map2_chr(.x, .y, .f, ...)`: Return a character vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map2_chr(l1, l2, paste, collapse = \",\", sep = \":\")\n ```\n :::\n\n\n- `map2_lgl(.x, .y, .f, ...)`: Return a logical vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map2_lgl(l2, l1, `%in%`)\n ```\n :::\n\n\n- `map2_dfc(.x, .y, .f, ...)`: Return a data frame created by column-binding.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map2_dfc(l1, l2, ~ as.data.frame(c(.x, .y)))\n ```\n :::\n\n\n- `map2_dfr(.x, .y, .f, ...)`: Return a data frame created by row-binding.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map2_dfr(l1, l2, ~ as.data.frame(c(.x, .y)))\n ```\n :::\n\n\n- `walk2(.x, .y, .f, ...)`: Trigger side effects, return invisibly.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n walk2(objs, paths, save)\n ```\n :::\n\n\n### Many Lists\n\n- `pmap(.l, .f, ...)`: Apply a function to groups of elements from a list of lists or vectors, return a list.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pmap(list(x, y, z), ~ ..1 * (..2 + ..3))\n ```\n :::\n\n\n- `pmap_dbl(.l, .f, ...)`: Return a double vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pmap_dbl(list(y, z), ~ .x / .y)\n ```\n :::\n\n\n- `pmap_int(.l, .f, ...)`: Return an integral vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pmap_int(list(y, z), `+`)\n ```\n :::\n\n\n- `pmap_chr(.l, .f, ...)`: Return a character vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pmap_chr(list(l1, l2), paste, collapse = \",\", sep = \":\")\n ```\n :::\n\n\n- `pmap_lgl(.l, .f, ...)`: Return a logical vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pmap_lgl(list(l2, l1), `%in%`)\n ```\n :::\n\n\n- `pmap_dfc(.l, .f, ...)`: Return a data frame created by column-binding.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pmap_dfc(list(l1, l2), ~ as.data.frame(c(.x, .y)))\n ```\n :::\n\n\n- `pmap_dfr(.l, .f, ...)`: Return a data frame created by row-binding.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pmap_dfr(list(l1, l2), ~ as.data.frame(c(.x, .y)))\n ```\n :::\n\n\n- `pwalk(.l, .f, ...)`: Trigger side effects, return invisibly.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pwalk(list(objs, paths), save)\n ```\n :::\n\n\n### Lists and Indexes\n\n- `imap(.x, .f, ...)`: Apply `.f` to each element and its index, return a list.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n imap(y, ~ paste0(.y, \": \", .x))\n ```\n :::\n\n\n- `imap_dbl(.x, .f, ...)`: Return a double vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n imap_dbl(y, ~ .y)\n ```\n :::\n\n\n- `imap_int(.x, .f, ...)`: Return an integral vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n imap_int(y, ~ .y)\n ```\n :::\n\n\n- `imap_chr(.x, .f, ...)`: Return a character vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n imap_chr(y, ~ paste0(.y, \": \", .x))\n ```\n :::\n\n\n- `imap_lgl(.x, .f, ...)`: Return a logical vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n imap_lgl(l1, ~ is.character(.y))\n ```\n :::\n\n\n- `imap_dfc(.x, .f, ...)`: Return a data frame created by column-binding.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n imap_dfc(l2, ~ as.data.frame(c(.x, .y)))\n ```\n :::\n\n\n- `imap_dfr(.x, .f, ...)`: Return a data frame created by row-binding.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n imap_dfr(l2, ~ as.data.frame(c(.x, .y)))\n ```\n :::\n\n\n- `iwalk(.x, .f, ...)`: Trigger side effects, return invisibly.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n iwalk(z, ~ print(paste0(.y, \": \", .x)))\n ```\n :::\n\n\n## Function Shortcuts\n\n- Use `~ .` with functions like `map()` that have single arguments.\n `map(l, ~ . + 2)` becomes `map(l, function(x) x + 2)`.\n\n- Use `~ .x .y` with functions like `map2()` that have two arguments.\n `map2(l, p, ~ .x + .y)` becomes `map2(l, p, function(l, p) l + p)`.\n\n- Use `~ ..1 ..2 ..3` etc with functions like `pmap()` that have many arguments.\n `pmap(list(a, b, c), ~ ..3 + ..1 - ..2)` becomes `pmap(list(a,b,c), function(a, b, c) c + a - b)`.\n\n- Use `~ .x .y` with functions like `imap()`.\n `.x` will get the list value and `.y` with get the index, or name if available.\n `imap(list(a, b, c), ~ paste0(.y, \": \", .x))` outputs `index: value` for each item.\n\n- Use a `string` or `integer` with any map function to index list elements by name or position.\n `map(l, \"name\")` becomes `map(l, function(x) x[[\"name\"]])`.\n\n\n\n## Work with Lists\n\n### Filter\n\n- `keep(.x, .p, ...)`: Select elements that pass a logical test.\n Conversely `discard()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n keep(x, is.numeric)\n ```\n :::\n\n\n- `compact(.x, .p = identity)`: Drop empty elements.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n compact(x)\n ```\n :::\n\n\n- `head_while(.x, .p, ...)`: Return head elements until one does not pass.\n Also `tail_while()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n head_while(x, is.character)\n ```\n :::\n\n\n- `detect(.x, .f, ..., dir = c(\"forward\", \"backward\"), .right = NULL)`: Find first element to pass.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n detect(x, is.character)\n ```\n :::\n\n\n- `detect_index(.x, .f, ..., dir = c(\"forward\", \"backward\"), .right = NULL)`: Find index of first element to pass.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n detect_index(x, is.character)\n ```\n :::\n\n\n- `every(.x, .p, ...)`: Do all elements pass a test?\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n every(x, is.character)\n ```\n :::\n\n\n- `some(.x, .p, ...)`: Do some elements pass a test?\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n some(x, is.character)\n ```\n :::\n\n\n- `none(.x, .p, ...)`: Do no elements pass a test?\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n none(x, is.character)\n ```\n :::\n\n\n- `has_element(.x, .y)`: Does a list contain an element?\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n has_element(x, \"foo\")\n ```\n :::\n\n\n- `pluck_depth(x)`: Return depth (number of levels of indexes).\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pluck_depth(x)\n ```\n :::\n\n\n### Index\n\n- `pluck(.x, ..., .deault = NULL)`: Select an element by name or index.\n Also `attr_getter()` and `chuck()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pluck(x, \"b\")\n x |> pluck(\"b\")\n ```\n :::\n\n\n- `assign_in(x, where, value)`: Assign a value to a location using pluck selection.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n assign_in(x, \"b\", 5)\n x |> assign_in(\"b\", 5)\n ```\n :::\n\n\n- `modify_in(.x, .where,, .f)`: Apply a function to a value at a selected location.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n modify_in(x, \"b\", abs)\n ```\n :::\n\n\n### Reshape\n\n- `flatten(.x)`: Remove a level of indexes from a list.\n Also `flatten_chr()` etc.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n flatten(x)\n ```\n :::\n\n\n- `array_tree(array, margin = NULL)`: Turn array into list.\n Also `array_branch()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n z <- array(1:12, c(2, 2, 2))\n array_tree(z, margin = 3)\n ```\n :::\n\n\n- `transpose(.l, .names = NULL)`: Transposes the index order in a multi-level list.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n transpose(x)\n ```\n :::\n\n\n- `set_names(x, nm = x)`: Set the names of a vector/list directly or with a function.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n set_names(x, c(\"p\", \"q\", \"r\"))\n set_names(x, tolower)\n ```\n :::\n\n\n### Modify\n\n- `modify(.x, .f, ...)`: Apply a function to each element.\n Also `modify2()` and `imodify()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n modify(x, ~ . + 2)\n ```\n :::\n\n\n- `modify_at(.x, .at, .f, ...)`: Apply a function to selected elements.\n Also `map_at()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n modify_at(x, \"b\", ~ . + 2)\n ```\n :::\n\n\n- `modify_if(.x, .p, .f, ...)`: Apply a function to elements that pass a test.\n Also `map_if()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n modify_if(x, is.numeric, ~ . + 2)\n ```\n :::\n\n\n- `modify_depth(.x, .depth, .f, ...)`: Apply function to each element at a given level of a list.\n Also `map_depth()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n modify_depth(x, 1, ~ . + 2)\n ```\n :::\n\n\n### Reduce\n\n- `reduce(.x, .f, ..., .init, .dir = c(\"forward\", \"backward\"))`: Apply function recursively to each element of a list of vector.\n Also `reduce2()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n a <- list(1, 2, 3, 4)\n reduce(a, sum)\n ```\n :::\n\n\n- `accumulate(.x, .f, ..., .init)`: Reduce a list, but also return intermediate results in a list.\n Also `accumulate2()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n a <- list(1, 2, 3, 4)\n accumulate(a, sum)\n ```\n :::\n\n\n### List-Columns\n\n**List-columns** are columns of a data frame where each element is a list or vector instead of an atomic value.\nColumns can also be lists of data frames.\nSee **tidyr** for more about nested data and list columns.\n\n#### Work With List-Columns\n\nManipulate list-columns like any other kind of column, using **dplyr** functions like `mutate()` and `transmute()`.\nBecause each element is a list, use **map functions** within a column function to manipulate each element.\n\n- `map()`, `map2()`, or `pmap()` return lists and will **create new list-columns**.\n In this example, `transmute()` is a column function, `map2()` is a list function which returns a list, and `vehicles` and `starships` are list-columns.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n dplyr::starwars |>\n dplyr::mutate(ships = map2(vehicles, starships, append))\n ```\n :::\n\n\n- Suffixed map functions like `map_int()` return an atomic data type and will **simplify list-columns into regular columns**.\n In this example, `mutate()` is a column function, `map_int()` is a list function which returns a column vector, and `films` is a list column.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n dplyr::starwars |>\n dplyr::mutate(n_films = map_int(films, length))\n ```\n :::\n\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [purrr.tidyverse.org](https://purrr.tidyverse.org).\n\nUpdated: 2023-05.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"purrr\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.0.1'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", + "markdown": "---\ntitle: \"Apply functions with purrr :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n message: true\n---\n\n::: {.cell .column-margin}\n\"Hex\n

\n

Download PDF

\n\"\"/\n
\n

Translations (PDF)

\n* Korean\n* Russian\n* Spanish\n* Ukrainian\n* Vietnamese\n:::\n\n\npurrr enhances R's functional programming (FP) toolkit by providing a complete and consistent set of tools for working with functions and vectors.\nIf you've never heard of FP before, the best place to start is the family of [`map()`](https://purrr.tidyverse.org/reference/map.html) functions which allow you to replace many for loops with code that is both more succinct and easier to read.\nThe best place to learn about the [`map()`](https://purrr.tidyverse.org/reference/map.html) functions is the [iteration chapter](https://r4ds.had.co.nz/iteration.html) in R for Data Science.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(purrr)\n```\n:::\n\n\n\n\n## Map Functions\n\n### One List\n\n- `map(.x, .f, ...)`: Apply a function to each element of a list of vector, and return a list.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n x <- list(a = 1:10, b = 11:20, c = 21:30)\n l1 <- list(x = c(\"a\", \"b\"), y = c(\"c\", \"d\"))\n map(l1, sort, decreasing = TRUE)\n ```\n :::\n\n\n- `map_dbl(.x, .f, ...)`: Return a double vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map_dbl(x, mean)\n ```\n :::\n\n\n- `map_int(.x, .f, ...)`: Return an integral vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map_int(x, length)\n ```\n :::\n\n\n- `map_chr(.x, .f, ...)`: Return a character vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map_chr(l1, paste, collapse = \"\")\n ```\n :::\n\n\n- `map_lgl(.x, .f, ...)`: Return a logical vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map_lgl(x, is.integer)\n ```\n :::\n\n\n- `map_dfc(.x, .f, ...)`: Return a data frame created by column-binding.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map_dfc(l1, rep, 3)\n ```\n :::\n\n\n- `map_dfr(.x, .f, ...)`: Return a data frame created by row-binding.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map_dfr(x, summary)\n ```\n :::\n\n\n- `walk(.x, .f, ...)`: Trigger side effects, return invisibly.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n walk(x, print)\n ```\n :::\n\n\n### Two Lists\n\n- `map2(.x, .y, .f, ...)`: Apply a function pairs of elements from two lists or vectors, return a list.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n y <- list(1, 2, 3)\n z <- list(4, 5, 6)\n l2 <- list(x = \"a\", y = \"z\")\n map2(x, y, ~ .x * .y)\n ```\n :::\n\n\n- `map2_dbl(.x, .y, .f, ...)`: Return a double vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map2_dbl(y, z, ~ .x / .y)\n ```\n :::\n\n\n- `map2_int(.x, .y, .f, ...)`: Return an integral vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map2_int(y, z, `+`)\n ```\n :::\n\n\n- `map2_chr(.x, .y, .f, ...)`: Return a character vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map2_chr(l1, l2, paste, collapse = \",\", sep = \":\")\n ```\n :::\n\n\n- `map2_lgl(.x, .y, .f, ...)`: Return a logical vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map2_lgl(l2, l1, `%in%`)\n ```\n :::\n\n\n- `map2_dfc(.x, .y, .f, ...)`: Return a data frame created by column-binding.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map2_dfc(l1, l2, ~ as.data.frame(c(.x, .y)))\n ```\n :::\n\n\n- `map2_dfr(.x, .y, .f, ...)`: Return a data frame created by row-binding.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n map2_dfr(l1, l2, ~ as.data.frame(c(.x, .y)))\n ```\n :::\n\n\n- `walk2(.x, .y, .f, ...)`: Trigger side effects, return invisibly.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n walk2(objs, paths, save)\n ```\n :::\n\n\n### Many Lists\n\n- `pmap(.l, .f, ...)`: Apply a function to groups of elements from a list of lists or vectors, return a list.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pmap(list(x, y, z), ~ ..1 * (..2 + ..3))\n ```\n :::\n\n\n- `pmap_dbl(.l, .f, ...)`: Return a double vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pmap_dbl(list(y, z), ~ .x / .y)\n ```\n :::\n\n\n- `pmap_int(.l, .f, ...)`: Return an integral vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pmap_int(list(y, z), `+`)\n ```\n :::\n\n\n- `pmap_chr(.l, .f, ...)`: Return a character vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pmap_chr(list(l1, l2), paste, collapse = \",\", sep = \":\")\n ```\n :::\n\n\n- `pmap_lgl(.l, .f, ...)`: Return a logical vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pmap_lgl(list(l2, l1), `%in%`)\n ```\n :::\n\n\n- `pmap_dfc(.l, .f, ...)`: Return a data frame created by column-binding.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pmap_dfc(list(l1, l2), ~ as.data.frame(c(.x, .y)))\n ```\n :::\n\n\n- `pmap_dfr(.l, .f, ...)`: Return a data frame created by row-binding.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pmap_dfr(list(l1, l2), ~ as.data.frame(c(.x, .y)))\n ```\n :::\n\n\n- `pwalk(.l, .f, ...)`: Trigger side effects, return invisibly.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pwalk(list(objs, paths), save)\n ```\n :::\n\n\n### Lists and Indexes\n\n- `imap(.x, .f, ...)`: Apply `.f` to each element and its index, return a list.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n imap(y, ~ paste0(.y, \": \", .x))\n ```\n :::\n\n\n- `imap_dbl(.x, .f, ...)`: Return a double vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n imap_dbl(y, ~ .y)\n ```\n :::\n\n\n- `imap_int(.x, .f, ...)`: Return an integral vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n imap_int(y, ~ .y)\n ```\n :::\n\n\n- `imap_chr(.x, .f, ...)`: Return a character vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n imap_chr(y, ~ paste0(.y, \": \", .x))\n ```\n :::\n\n\n- `imap_lgl(.x, .f, ...)`: Return a logical vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n imap_lgl(l1, ~ is.character(.y))\n ```\n :::\n\n\n- `imap_dfc(.x, .f, ...)`: Return a data frame created by column-binding.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n imap_dfc(l2, ~ as.data.frame(c(.x, .y)))\n ```\n :::\n\n\n- `imap_dfr(.x, .f, ...)`: Return a data frame created by row-binding.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n imap_dfr(l2, ~ as.data.frame(c(.x, .y)))\n ```\n :::\n\n\n- `iwalk(.x, .f, ...)`: Trigger side effects, return invisibly.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n iwalk(z, ~ print(paste0(.y, \": \", .x)))\n ```\n :::\n\n\n## Function Shortcuts\n\n- Use `~ .` with functions like `map()` that have single arguments.\n `map(l, ~ . + 2)` becomes `map(l, function(x) x + 2)`.\n\n- Use `~ .x .y` with functions like `map2()` that have two arguments.\n `map2(l, p, ~ .x + .y)` becomes `map2(l, p, function(l, p) l + p)`.\n\n- Use `~ ..1 ..2 ..3` etc with functions like `pmap()` that have many arguments.\n `pmap(list(a, b, c), ~ ..3 + ..1 - ..2)` becomes `pmap(list(a,b,c), function(a, b, c) c + a - b)`.\n\n- Use `~ .x .y` with functions like `imap()`.\n `.x` will get the list value and `.y` with get the index, or name if available.\n `imap(list(a, b, c), ~ paste0(.y, \": \", .x))` outputs `index: value` for each item.\n\n- Use a `string` or `integer` with any map function to index list elements by name or position.\n `map(l, \"name\")` becomes `map(l, function(x) x[[\"name\"]])`.\n\n\n\n## Work with Lists\n\n### Filter\n\n- `keep(.x, .p, ...)`: Select elements that pass a logical test.\n Conversely `discard()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n keep(x, is.numeric)\n ```\n :::\n\n\n- `compact(.x, .p = identity)`: Drop empty elements.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n compact(x)\n ```\n :::\n\n\n- `head_while(.x, .p, ...)`: Return head elements until one does not pass.\n Also `tail_while()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n head_while(x, is.character)\n ```\n :::\n\n\n- `detect(.x, .f, ..., dir = c(\"forward\", \"backward\"), .right = NULL)`: Find first element to pass.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n detect(x, is.character)\n ```\n :::\n\n\n- `detect_index(.x, .f, ..., dir = c(\"forward\", \"backward\"), .right = NULL)`: Find index of first element to pass.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n detect_index(x, is.character)\n ```\n :::\n\n\n- `every(.x, .p, ...)`: Do all elements pass a test?\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n every(x, is.character)\n ```\n :::\n\n\n- `some(.x, .p, ...)`: Do some elements pass a test?\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n some(x, is.character)\n ```\n :::\n\n\n- `none(.x, .p, ...)`: Do no elements pass a test?\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n none(x, is.character)\n ```\n :::\n\n\n- `has_element(.x, .y)`: Does a list contain an element?\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n has_element(x, \"foo\")\n ```\n :::\n\n\n- `pluck_depth(x)`: Return depth (number of levels of indexes).\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pluck_depth(x)\n ```\n :::\n\n\n### Index\n\n- `pluck(.x, ..., .deault = NULL)`: Select an element by name or index.\n Also `attr_getter()` and `chuck()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pluck(x, \"b\")\n x |> pluck(\"b\")\n ```\n :::\n\n\n- `assign_in(x, where, value)`: Assign a value to a location using pluck selection.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n assign_in(x, \"b\", 5)\n x |> assign_in(\"b\", 5)\n ```\n :::\n\n\n- `modify_in(.x, .where,, .f)`: Apply a function to a value at a selected location.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n modify_in(x, \"b\", abs)\n ```\n :::\n\n\n### Reshape\n\n- `flatten(.x)`: Remove a level of indexes from a list.\n Also `flatten_chr()` etc.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n flatten(x)\n ```\n :::\n\n\n- `array_tree(array, margin = NULL)`: Turn array into list.\n Also `array_branch()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n z <- array(1:12, c(2, 2, 2))\n array_tree(z, margin = 3)\n ```\n :::\n\n\n- `transpose(.l, .names = NULL)`: Transposes the index order in a multi-level list.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n transpose(x)\n ```\n :::\n\n\n- `set_names(x, nm = x)`: Set the names of a vector/list directly or with a function.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n set_names(x, c(\"p\", \"q\", \"r\"))\n set_names(x, tolower)\n ```\n :::\n\n\n### Modify\n\n- `modify(.x, .f, ...)`: Apply a function to each element.\n Also `modify2()` and `imodify()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n modify(x, ~ . + 2)\n ```\n :::\n\n\n- `modify_at(.x, .at, .f, ...)`: Apply a function to selected elements.\n Also `map_at()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n modify_at(x, \"b\", ~ . + 2)\n ```\n :::\n\n\n- `modify_if(.x, .p, .f, ...)`: Apply a function to elements that pass a test.\n Also `map_if()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n modify_if(x, is.numeric, ~ . + 2)\n ```\n :::\n\n\n- `modify_depth(.x, .depth, .f, ...)`: Apply function to each element at a given level of a list.\n Also `map_depth()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n modify_depth(x, 1, ~ . + 2)\n ```\n :::\n\n\n### Reduce\n\n- `reduce(.x, .f, ..., .init, .dir = c(\"forward\", \"backward\"))`: Apply function recursively to each element of a list of vector.\n Also `reduce2()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n a <- list(1, 2, 3, 4)\n reduce(a, sum)\n ```\n :::\n\n\n- `accumulate(.x, .f, ..., .init)`: Reduce a list, but also return intermediate results in a list.\n Also `accumulate2()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n a <- list(1, 2, 3, 4)\n accumulate(a, sum)\n ```\n :::\n\n\n### List-Columns\n\n**List-columns** are columns of a data frame where each element is a list or vector instead of an atomic value.\nColumns can also be lists of data frames.\nSee **tidyr** for more about nested data and list columns.\n\n#### Work With List-Columns\n\nManipulate list-columns like any other kind of column, using **dplyr** functions like `mutate()` and `transmute()`.\nBecause each element is a list, use **map functions** within a column function to manipulate each element.\n\n- `map()`, `map2()`, or `pmap()` return lists and will **create new list-columns**.\n In this example, `transmute()` is a column function, `map2()` is a list function which returns a list, and `vehicles` and `starships` are list-columns.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n dplyr::starwars |>\n dplyr::mutate(ships = map2(vehicles, starships, append))\n ```\n :::\n\n\n- Suffixed map functions like `map_int()` return an atomic data type and will **simplify list-columns into regular columns**.\n In this example, `mutate()` is a column function, `map_int()` is a list function which returns a column vector, and `films` is a list column.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n dplyr::starwars |>\n dplyr::mutate(n_films = map_int(films, length))\n ```\n :::\n\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [purrr.tidyverse.org](https://purrr.tidyverse.org).\n\nUpdated: 2023-06.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"purrr\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.0.1'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", "supporting": [], "filters": [ "rmarkdown/pagebreak.lua" diff --git a/_freeze/html/reticulate/execute-results/html.json b/_freeze/html/reticulate/execute-results/html.json index 3ff7a724..12ae67b0 100644 --- a/_freeze/html/reticulate/execute-results/html.json +++ b/_freeze/html/reticulate/execute-results/html.json @@ -1,7 +1,7 @@ { - "hash": "bb01269d19f2b245673a8b22c1ce0548", + "hash": "0b954615dc3e220b814fc6189c185da2", "result": { - "markdown": "---\ntitle: \"Use Python with R with reticulate :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: false\n output: false\n warning: false\n---\n\n::: {.cell .column-margin}\n\"\"\n

\n

Download PDF

\n\n
\n

Translations (PDF)

\n* Spanish\n:::\n\n\nThe **reticulate** package lets you use Python and R together seamlessly in R code, in R Markdown documents, and in the RStudio IDE.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(reticulate)\n```\n:::\n\n\n## Python in R Markdown\n\n(Optional) Build Python env to use.\n\nAdd `knitr::knit_engires$set(python = reticulate::eng_python)` to the setup chunk to set up the reticulate Python engine (not required for knitr \\>= 1.18).\n\n```{{{r}}}\n#| label: setup\n#| include: false\n\nlibrary(reticulate) \nvirtualenv_create(\"fmri-proj\") \npy_install(\"seaborn\", envname = \"fmri-proj\") \nuse_virtualenv(\"fmri-proj\")`\n```\n\nBegin Python chunks with ```` ```{python} ````.\nChunk options like `echo`, `include`, etc. all work as expected.\n\n```{{{python}}} \n#| echo: false\n\nimport seaborn as sns \nfmri = sns.load_dataset(\"fmri\")`\n```\n\nUse the `py` object the access objects created in Python chunks from R chunks.\n\n```` \n``` {{r}}\nf1 <- subset(py$fmri, region = \"parietal\")\n```\n````\n\nPython chunks all execute within a **single** Python session so you have access to all objects created in previous chunks.\n\nUse the `r` object to access objects created in R chunks from Python chunks.\n\n```` \n``` {{python}}\nimport matplotlib as mpl\nsns.lmplot(\"timepoint\", \"signal\", data=r.f1)\nmpl.pyplot.show()\n```\n````\n\n## Python in R\n\n`python.r` Example:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(reticulate)\npy_install(\"seaborn\")\nuse_virtualenv(\"r-reticulate\")\n\nsns <- import(\"seaborn\")\n\nfmri <- sns$load_dataset(\"fmri\")\ndim(fmri)\n\n# creates tips\nsource_python(\"python.py\")\ndim(tips)\n\n# creates tips in main\npy_run_file(\"python.py\")\ndim(py$tips)\n\npy_run_string(\"print(tips.shape)\")\n```\n:::\n\n\n`python.py` Example:\n\n``` python\nimport seaborn as sns\ntips = sns.load_dataset(\"tips\")\n```\n\nCall Python from R code in three ways:\n\n### Import Python Modules\n\nUse `import()` to import any Python module.\nAccess the attributes of a module with `$`.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(reticulate)\npy_install(\"seaborn\")\nuse_virtualenv(\"r-reticulate\")\n\nsns <- import(\"seaborn\")\n\ntips <- sns$load_dataset(\"tips\")\ndim(tips)\n```\n:::\n\n\n- `import(module, as = NULL, convert = TRUE, delay_load = FALSE)`: Import a Python module.\n If `convert = TRUE`, Python objects are converted to their equivalent R types.\n Also `import_from_path()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n import(\"pandas\")\n ```\n :::\n\n\n- `import_main(convert = TRUE)`: Import the main module, where Python executes code by default.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n import_main()\n ```\n :::\n\n\n- `import_builtings(convert = TRUE)`: Import Python's built-in functions.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n import_builtins()\n ```\n :::\n\n\n### Source Python Files\n\nUse `source_python()` to source a Python script and make the Python functions and objects it creates available in the calling R environment.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nsource_python(\"python.py\")\ndim(py$tips)\n```\n:::\n\n\n- `source_python(file, envir = parent.frame(), convert = TRUE)`: Run a Python script, assigning objects to a specified R environment.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n source_python(\"python.py\")\n ```\n :::\n\n\n### Run Python Code\n\nExecute Python code into the `main` Python modules with `py_run_file()` or `py_run_string()`.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npy_run_file(\"python.py\")\ndim(py$tips)\n\npy_run_string(\"print(tips.shape)\")\n```\n:::\n\n\n- `py_run_string(code, local = FALSE, convert = TRUE)`: Run Python code (passed as a string) in the main module.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_run_string(\"x = 10\")\n py$x\n ```\n :::\n\n\n- `py_run_file(file, local = FALSE, convert = TRUE)`: Run Python file in the main module.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_run_file(\"python.py\")\n ```\n :::\n\n\n- `py_eval(code, convert = TRUE)`: Run a Python expression, return the result.\n Also `py_call()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_eval(\"1 + 1\")\n ```\n :::\n\n\nAccess the results, and anything else in Python's `main` module, with `py`.\n\n- `py`: An R object that contains the Python main module and the results stored there.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py$x\n ```\n :::\n\n\n## Object Conversion\n\n**Tip: To index Python objects begin at 0, use integers, e.g. `OL`**\n\nReticulate provides **automatic** built-in conversion between Python and R for many Python types.\n\n| R | Python |\n|------------------------|-------------------|\n| Single-element vector | Scalar |\n| Multi-element vector | List |\n| List of multiple types | Tuple |\n| Named List | Dict |\n| Matrix/Array | NumPy ndarray |\n| Data Frame | Pandas DataFrame |\n| Function | Python function |\n| NULL, TRUE, FALSE | None, True, False |\n\n: Table of data types in R and their Python equivalents.\n\nOr, if you like, you can convert manually with\n\n- `py_to_r(x)`: Convert a Python object to an R object.\n Also `r_to_py()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_to_r(py)\n ```\n :::\n\n\n- `tuple(..., convert = FALSE)`: Create a Python tuple.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n tuple(\"a\", \"b\", \"c\")\n ```\n :::\n\n\n- `dict(..., convert = FALSE)`: Create a Python dictionary object.\n Also `py_dict()` to make a dictionary that uses Python objects as keys.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n dict(foo = \"bar\", index = 42L)\n ```\n :::\n\n\n- `np_array(data, dtype = NULL, order = \"C\")`: Create NumPy arrays.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n np_array(c(1:8), dtype = \"float16\")\n ```\n :::\n\n\n- `array_reshape(x, dim, order = c(\"C\", \"F\"))`: Reshape a Python array.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n x <- 1:4\n array_reshape(x, c(2,2))\n ```\n :::\n\n\n- `py_func(f)`: Wrap an R function in a Python function with the same signature.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_func(xor)\n ```\n :::\n\n\n- `py_main_thread_func(f)`: Create a function that will always be called on the main thread.\n\n- `iterate(it, f = base::identity, simplify = TRUE)`: Apply an R function to each value of a Python iterator or return the values as an R vector, draining the iterator as you go.\n Also `iter_next()` and `as_iterator()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n iterate(iter, print)\n ```\n :::\n\n\n- `py_interator(fn, completed = NULL)`: Create a Python iterator from an R function.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n seq_gen <- function(x) {\n n <- x;\n function() {\n n <<- n + 1;\n n\n }\n }\n py_iterator(seq_gen(9))\n ```\n :::\n\n\n## Helpers\n\n- `py_capture_output(expr, type = c(\"stdout\", \"stderr\"))`: Capture and return Python output.\n Also `py_supress_warnings()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_capture_output(\"x\")\n ```\n :::\n\n\n- `py_get_attr(x, name, silent = FALSE)`: Get an attribute of a Python object.\n Also `py_set_attr()`, `py_has_attr()`, and `py_list_attributes()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_get_attr(x)\n ```\n :::\n\n\n\n\n- `py_help(object)`: Open the documentation page for a Python object.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_help(sns)\n ```\n :::\n\n\n- `py_last_error()`: Get the last Python error encountered.\n Also `py_clear_last_error()` to clear the last error.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_last_error()\n ```\n :::\n\n\n- `py_save_object(object, filename, pickle = \"pickle\", ...)`: Save and load Python objects with pickle.\n Also `py_load_object()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_save_objects(x, \"x.pickle\")\n ```\n :::\n\n\n- `with(data, expr, as = NULL, ...)`: Evaluate an expression within a Python context manager.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py <- import_builtins()\n with(py$open(\"output.txt\", \"w\") %as% file,\n {file$write(\"Hello, there!\")})\n ```\n :::\n\n\n\n\n## Python in the IDE\n\nRequires reticulate plus RStudio v1.2+.\nSome features require v1.4+.\n\n![](images/reticulate-ide.png)\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about reticulate features in the RStudio IDE {aria-hidden=\"true\"}\n\n### reticulate features in the RStudio IDE\n\n- Syntax highlighting for Python scripts and chunks.\n- Tab completion for Python functions and objects (and Python modules imported in R scripts).\n- Source Python scripts.\n- Execute Python code line by line with `Cmd + Enter` (`Ctrl + Enter`).\n- View Python objects in the Environment Pane.\n- View Python objects in the Data Viewer.\n- A Python REPL opens in the console when you run Python code with a keyboard shortcut. Type `exit` to close.\n- `matplotlib` plots display in plots pane.\n- Press `F1` over a Python symbol to display the help topic for that symbol.\n:::\n\n## Python REPL\n\nRStudio IDE Window:\n\nA REPL (Read, Eval, Print Loop) is a command line where you can run Python code and view the results.\n\n1. Open in the console with `repl_python()`, or by running code in a Python script with `Cmd + Enter` (`Ctrl + Enter`).\n\n - `repl_python(module = NULL, quiet = getOption(\"reticulate.repl.quiet\", default = FALSE), input = NULL)`: Launch a Python REPL. Run `exit` to close.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n repl_python()\n ```\n :::\n\n\n2. Type commands at `>>>` prompt.\n\n3. Press `Enter` to run code.\n\n4. Type `exit` to close and return to R console.\n\n ``` \n > reticulate::repl_python()\n Python 3.9.16 (/Users/mine/.virtualenvs/r-reticulate/bin/python)\n Reticulate 1.28 REPL -- A Python interpreter in R.\n Enter 'exit' or 'quit' to exit the REPL and return to R.\n >>> import seaborn as sns\n >>> tips = sns.load_dataset(\"tips\")\n >>> tips.shape\n (244, 7)\n >>> exit\n >\n ```\n\n## Configure Python\n\nReticulate binds to a local instance of Python when you first call `import()` directly or implicitly from an R session.\nTo control the process, find or build your desired Python instance.\nThen suggest your instance to reticulate.\n**Restart R to unbind.**\n\n### Find Python\n\n- `install_python(version, list = FALSE, force = FALSE)`: Download and install Python.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n install_python(\"3.9.16\")\n ```\n :::\n\n\n- `py_available(initialize = FALSE)`: Check if Python is available on your system.\n Also `py_module_available()` and `py_numpy_module()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_available()\n ```\n :::\n\n\n- `py_discover_config()`: Return all detected versions of Python.\n Use `py_config()` to check which version has been loaded.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_config()\n ```\n :::\n\n\n- `virtualenv_list()`: List all available virtual environments.\n Also `virtualenv_root()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n virtualenv_list()\n ```\n :::\n\n\n- `conda_list(conda = \"auto\")`: List all available conda envs.\n Also `conda_binary()` and `conda_version()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n conda_list()\n ```\n :::\n\n\n### Create a Python env\n\n- `virtual_env(envname = NULL, ...)`: Create a new virtual environment.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n virtualenv_create(\"r-pandas\")\n ```\n :::\n\n\n- `conda_create(envname = NULL, ...)`: Create a new conda environment.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n conda_create(\"r-pandas\", packages = \"pandas\")\n ```\n :::\n\n\n### Install Packages\n\nInstall Python packages with R (below) or the shell:\n\n`pip install SciPy`\n\n`conda install SciPy`\n\n- `py_install(packages, envname, ...)`: Install Python packages into a Python env.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_install(\"pandas\")\n ```\n :::\n\n\n- `virtualenv_install(envname, packages, ...)`: Install a package within a virtual environment.\n Also `virtualenv_remove()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n virtualenv_install(\"r-pandas\", packages = \"pandas\")\n ```\n :::\n\n\n- `conda_installs(envname, packages, ...)`: Install a package within a conda environment.\n Also `conda_remove()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n conda_install(\"r-pandas\", packages = \"plotly\")\n ```\n :::\n\n\n### Suggest an env to use\n\nSet a default Python interpreter in the RStudio IDE Global or Project Options.\nGo to **Tools \\> Global Options ... \\> Python** for Global Options.\nWithin a project, go to **Tools \\> Project Options... \\> Python**.\n\nOtherwise, to choose an instance of Python to bind to, reticulate scans the instances on your computer in the following order, **stopping at the first instance that contains the module called by `import()`**.\n\n1. The instance referenced by the environment variable `RETICULATE_PYTHON` (if specified).\n **Tip: set in .Renviron file.**\n\n - `Sys.setenv(RETICULATE_PYTHON = PATH)`: Set default Python binary.\n Persists across sessions!\n Undo with `Sys.unsetenv()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n Sys.setenv(RETICULATE_PYTHON = \"/usr/local/bin/python\")\n ```\n :::\n\n\n2. The instances referenced by `use_` functions if called before `import()`.\n Will fail silently if called after impoty unless `required = TRUE`.\n\n - `use_python(python, required = FALSE)`: Suggest a Python binary to use by path.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n use_python(\"usr/local/bin/python\")\n ```\n :::\n\n\n - `use_virtualenv(virtualenv = NULL, required = FALSE)`: Suggest a Python virtualenv\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n use_virtualenv(\"~/myenv\")\n ```\n :::\n\n\n - `use_condaenv(condaenv = NULL, conda = \"auto\", required = FALSE)`: Suggest a conda env to use.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n use_condaenv(condaenv = \"r-nlp\", conda = \"/opt/anaconda3/bin/conda\")\n ```\n :::\n\n\n3. Within virtualenvs and conda envs that carry the same name as the imported module.\n e.g. `~/anaconda/envs/nltk` for `import(\"nltk\")`\n\n4. At the location of the Python binary discovered on the system PATH (i.e. `Sys.which(\"python\")`)\n\n5. At customary locations for Python, e.g. `/usr/local/bin/python`, `/opt/local/bin/python…`\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [rstudio.github.io/reticulate](https://rstudio.github.io/reticulate/).\n\nUpdated: 2023-05.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"reticulate\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.28'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", + "markdown": "---\ntitle: \"Use Python with R with reticulate :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: false\n output: false\n warning: false\n---\n\n::: {.cell .column-margin}\n\"Hex\n

\n

Download PDF

\n\"\"/\n
\n

Translations (PDF)

\n* Spanish\n:::\n\n\nThe **reticulate** package lets you use Python and R together seamlessly in R code, in R Markdown documents, and in the RStudio IDE.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(reticulate)\n```\n:::\n\n\n## Python in R Markdown\n\n(Optional) Build Python env to use.\n\nAdd `knitr::knit_engires$set(python = reticulate::eng_python)` to the setup chunk to set up the reticulate Python engine (not required for knitr \\>= 1.18).\n\n```{{{r}}}\n#| label: setup\n#| include: false\n\nlibrary(reticulate) \nvirtualenv_create(\"fmri-proj\") \npy_install(\"seaborn\", envname = \"fmri-proj\") \nuse_virtualenv(\"fmri-proj\")`\n```\n\nBegin Python chunks with ```` ```{python} ````.\nChunk options like `echo`, `include`, etc. all work as expected.\n\n```{{{python}}} \n#| echo: false\n\nimport seaborn as sns \nfmri = sns.load_dataset(\"fmri\")`\n```\n\nUse the `py` object the access objects created in Python chunks from R chunks.\n\n```` \n``` {{r}}\nf1 <- subset(py$fmri, region = \"parietal\")\n```\n````\n\nPython chunks all execute within a **single** Python session so you have access to all objects created in previous chunks.\n\nUse the `r` object to access objects created in R chunks from Python chunks.\n\n```` \n``` {{python}}\nimport matplotlib as mpl\nsns.lmplot(\"timepoint\", \"signal\", data=r.f1)\nmpl.pyplot.show()\n```\n````\n\n## Python in R\n\n`python.r` Example:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(reticulate)\npy_install(\"seaborn\")\nuse_virtualenv(\"r-reticulate\")\n\nsns <- import(\"seaborn\")\n\nfmri <- sns$load_dataset(\"fmri\")\ndim(fmri)\n\n# creates tips\nsource_python(\"python.py\")\ndim(tips)\n\n# creates tips in main\npy_run_file(\"python.py\")\ndim(py$tips)\n\npy_run_string(\"print(tips.shape)\")\n```\n:::\n\n\n`python.py` Example:\n\n``` python\nimport seaborn as sns\ntips = sns.load_dataset(\"tips\")\n```\n\nCall Python from R code in three ways:\n\n### Import Python Modules\n\nUse `import()` to import any Python module.\nAccess the attributes of a module with `$`.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(reticulate)\npy_install(\"seaborn\")\nuse_virtualenv(\"r-reticulate\")\n\nsns <- import(\"seaborn\")\n\ntips <- sns$load_dataset(\"tips\")\ndim(tips)\n```\n:::\n\n\n- `import(module, as = NULL, convert = TRUE, delay_load = FALSE)`: Import a Python module.\n If `convert = TRUE`, Python objects are converted to their equivalent R types.\n Also `import_from_path()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n import(\"pandas\")\n ```\n :::\n\n\n- `import_main(convert = TRUE)`: Import the main module, where Python executes code by default.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n import_main()\n ```\n :::\n\n\n- `import_builtings(convert = TRUE)`: Import Python's built-in functions.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n import_builtins()\n ```\n :::\n\n\n### Source Python Files\n\nUse `source_python()` to source a Python script and make the Python functions and objects it creates available in the calling R environment.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nsource_python(\"python.py\")\ndim(py$tips)\n```\n:::\n\n\n- `source_python(file, envir = parent.frame(), convert = TRUE)`: Run a Python script, assigning objects to a specified R environment.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n source_python(\"python.py\")\n ```\n :::\n\n\n### Run Python Code\n\nExecute Python code into the `main` Python modules with `py_run_file()` or `py_run_string()`.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npy_run_file(\"python.py\")\ndim(py$tips)\n\npy_run_string(\"print(tips.shape)\")\n```\n:::\n\n\n- `py_run_string(code, local = FALSE, convert = TRUE)`: Run Python code (passed as a string) in the main module.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_run_string(\"x = 10\")\n py$x\n ```\n :::\n\n\n- `py_run_file(file, local = FALSE, convert = TRUE)`: Run Python file in the main module.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_run_file(\"python.py\")\n ```\n :::\n\n\n- `py_eval(code, convert = TRUE)`: Run a Python expression, return the result.\n Also `py_call()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_eval(\"1 + 1\")\n ```\n :::\n\n\nAccess the results, and anything else in Python's `main` module, with `py`.\n\n- `py`: An R object that contains the Python main module and the results stored there.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py$x\n ```\n :::\n\n\n## Object Conversion\n\n**Tip: To index Python objects begin at 0, use integers, e.g. `OL`**\n\nReticulate provides **automatic** built-in conversion between Python and R for many Python types.\n\n| R | Python |\n|------------------------|-------------------|\n| Single-element vector | Scalar |\n| Multi-element vector | List |\n| List of multiple types | Tuple |\n| Named List | Dict |\n| Matrix/Array | NumPy ndarray |\n| Data Frame | Pandas DataFrame |\n| Function | Python function |\n| NULL, TRUE, FALSE | None, True, False |\n\n: Table of data types in R and their Python equivalents.\n\nOr, if you like, you can convert manually with\n\n- `py_to_r(x)`: Convert a Python object to an R object.\n Also `r_to_py()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_to_r(py)\n ```\n :::\n\n\n- `tuple(..., convert = FALSE)`: Create a Python tuple.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n tuple(\"a\", \"b\", \"c\")\n ```\n :::\n\n\n- `dict(..., convert = FALSE)`: Create a Python dictionary object.\n Also `py_dict()` to make a dictionary that uses Python objects as keys.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n dict(foo = \"bar\", index = 42L)\n ```\n :::\n\n\n- `np_array(data, dtype = NULL, order = \"C\")`: Create NumPy arrays.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n np_array(c(1:8), dtype = \"float16\")\n ```\n :::\n\n\n- `array_reshape(x, dim, order = c(\"C\", \"F\"))`: Reshape a Python array.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n x <- 1:4\n array_reshape(x, c(2,2))\n ```\n :::\n\n\n- `py_func(f)`: Wrap an R function in a Python function with the same signature.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_func(xor)\n ```\n :::\n\n\n- `py_main_thread_func(f)`: Create a function that will always be called on the main thread.\n\n- `iterate(it, f = base::identity, simplify = TRUE)`: Apply an R function to each value of a Python iterator or return the values as an R vector, draining the iterator as you go.\n Also `iter_next()` and `as_iterator()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n iterate(iter, print)\n ```\n :::\n\n\n- `py_interator(fn, completed = NULL)`: Create a Python iterator from an R function.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n seq_gen <- function(x) {\n n <- x;\n function() {\n n <<- n + 1;\n n\n }\n }\n py_iterator(seq_gen(9))\n ```\n :::\n\n\n## Helpers\n\n- `py_capture_output(expr, type = c(\"stdout\", \"stderr\"))`: Capture and return Python output.\n Also `py_supress_warnings()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_capture_output(\"x\")\n ```\n :::\n\n\n- `py_get_attr(x, name, silent = FALSE)`: Get an attribute of a Python object.\n Also `py_set_attr()`, `py_has_attr()`, and `py_list_attributes()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_get_attr(x)\n ```\n :::\n\n\n\n\n- `py_help(object)`: Open the documentation page for a Python object.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_help(sns)\n ```\n :::\n\n\n- `py_last_error()`: Get the last Python error encountered.\n Also `py_clear_last_error()` to clear the last error.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_last_error()\n ```\n :::\n\n\n- `py_save_object(object, filename, pickle = \"pickle\", ...)`: Save and load Python objects with pickle.\n Also `py_load_object()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_save_objects(x, \"x.pickle\")\n ```\n :::\n\n\n- `with(data, expr, as = NULL, ...)`: Evaluate an expression within a Python context manager.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py <- import_builtins()\n with(py$open(\"output.txt\", \"w\") %as% file,\n {file$write(\"Hello, there!\")})\n ```\n :::\n\n\n\n\n## Python in the IDE\n\nRequires reticulate plus RStudio v1.2+.\nSome features require v1.4+.\n\n![](images/reticulate-ide.png)\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about reticulate features in the RStudio IDE {aria-hidden=\"true\"}\n\n### reticulate features in the RStudio IDE\n\n- Syntax highlighting for Python scripts and chunks.\n- Tab completion for Python functions and objects (and Python modules imported in R scripts).\n- Source Python scripts.\n- Execute Python code line by line with `Cmd + Enter` (`Ctrl + Enter`).\n- View Python objects in the Environment Pane.\n- View Python objects in the Data Viewer.\n- A Python REPL opens in the console when you run Python code with a keyboard shortcut. Type `exit` to close.\n- `matplotlib` plots display in plots pane.\n- Press `F1` over a Python symbol to display the help topic for that symbol.\n:::\n\n## Python REPL\n\nRStudio IDE Window:\n\nA REPL (Read, Eval, Print Loop) is a command line where you can run Python code and view the results.\n\n1. Open in the console with `repl_python()`, or by running code in a Python script with `Cmd + Enter` (`Ctrl + Enter`).\n\n - `repl_python(module = NULL, quiet = getOption(\"reticulate.repl.quiet\", default = FALSE), input = NULL)`: Launch a Python REPL. Run `exit` to close.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n repl_python()\n ```\n :::\n\n\n2. Type commands at `>>>` prompt.\n\n3. Press `Enter` to run code.\n\n4. Type `exit` to close and return to R console.\n\n ``` \n > reticulate::repl_python()\n Python 3.9.16 (/Users/mine/.virtualenvs/r-reticulate/bin/python)\n Reticulate 1.28 REPL -- A Python interpreter in R.\n Enter 'exit' or 'quit' to exit the REPL and return to R.\n >>> import seaborn as sns\n >>> tips = sns.load_dataset(\"tips\")\n >>> tips.shape\n (244, 7)\n >>> exit\n >\n ```\n\n## Configure Python\n\nReticulate binds to a local instance of Python when you first call `import()` directly or implicitly from an R session.\nTo control the process, find or build your desired Python instance.\nThen suggest your instance to reticulate.\n**Restart R to unbind.**\n\n### Find Python\n\n- `install_python(version, list = FALSE, force = FALSE)`: Download and install Python.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n install_python(\"3.9.16\")\n ```\n :::\n\n\n- `py_available(initialize = FALSE)`: Check if Python is available on your system.\n Also `py_module_available()` and `py_numpy_module()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_available()\n ```\n :::\n\n\n- `py_discover_config()`: Return all detected versions of Python.\n Use `py_config()` to check which version has been loaded.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_config()\n ```\n :::\n\n\n- `virtualenv_list()`: List all available virtual environments.\n Also `virtualenv_root()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n virtualenv_list()\n ```\n :::\n\n\n- `conda_list(conda = \"auto\")`: List all available conda envs.\n Also `conda_binary()` and `conda_version()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n conda_list()\n ```\n :::\n\n\n### Create a Python env\n\n- `virtual_env(envname = NULL, ...)`: Create a new virtual environment.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n virtualenv_create(\"r-pandas\")\n ```\n :::\n\n\n- `conda_create(envname = NULL, ...)`: Create a new conda environment.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n conda_create(\"r-pandas\", packages = \"pandas\")\n ```\n :::\n\n\n### Install Packages\n\nInstall Python packages with R (below) or the shell:\n\n`pip install SciPy`\n\n`conda install SciPy`\n\n- `py_install(packages, envname, ...)`: Install Python packages into a Python env.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n py_install(\"pandas\")\n ```\n :::\n\n\n- `virtualenv_install(envname, packages, ...)`: Install a package within a virtual environment.\n Also `virtualenv_remove()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n virtualenv_install(\"r-pandas\", packages = \"pandas\")\n ```\n :::\n\n\n- `conda_installs(envname, packages, ...)`: Install a package within a conda environment.\n Also `conda_remove()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n conda_install(\"r-pandas\", packages = \"plotly\")\n ```\n :::\n\n\n### Suggest an env to use\n\nSet a default Python interpreter in the RStudio IDE Global or Project Options.\nGo to **Tools \\> Global Options ... \\> Python** for Global Options.\nWithin a project, go to **Tools \\> Project Options... \\> Python**.\n\nOtherwise, to choose an instance of Python to bind to, reticulate scans the instances on your computer in the following order, **stopping at the first instance that contains the module called by `import()`**.\n\n1. The instance referenced by the environment variable `RETICULATE_PYTHON` (if specified).\n **Tip: set in .Renviron file.**\n\n - `Sys.setenv(RETICULATE_PYTHON = PATH)`: Set default Python binary.\n Persists across sessions!\n Undo with `Sys.unsetenv()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n Sys.setenv(RETICULATE_PYTHON = \"/usr/local/bin/python\")\n ```\n :::\n\n\n2. The instances referenced by `use_` functions if called before `import()`.\n Will fail silently if called after impoty unless `required = TRUE`.\n\n - `use_python(python, required = FALSE)`: Suggest a Python binary to use by path.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n use_python(\"usr/local/bin/python\")\n ```\n :::\n\n\n - `use_virtualenv(virtualenv = NULL, required = FALSE)`: Suggest a Python virtualenv\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n use_virtualenv(\"~/myenv\")\n ```\n :::\n\n\n - `use_condaenv(condaenv = NULL, conda = \"auto\", required = FALSE)`: Suggest a conda env to use.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n use_condaenv(condaenv = \"r-nlp\", conda = \"/opt/anaconda3/bin/conda\")\n ```\n :::\n\n\n3. Within virtualenvs and conda envs that carry the same name as the imported module.\n e.g. `~/anaconda/envs/nltk` for `import(\"nltk\")`\n\n4. At the location of the Python binary discovered on the system PATH (i.e. `Sys.which(\"python\")`)\n\n5. At customary locations for Python, e.g. `/usr/local/bin/python`, `/opt/local/bin/python…`\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [rstudio.github.io/reticulate](https://rstudio.github.io/reticulate/).\n\nUpdated: 2023-06.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"reticulate\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.28'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", "supporting": [], "filters": [ "rmarkdown/pagebreak.lua" diff --git a/_freeze/html/rmarkdown/execute-results/html.json b/_freeze/html/rmarkdown/execute-results/html.json index b4fe2fc7..ab3a539e 100644 --- a/_freeze/html/rmarkdown/execute-results/html.json +++ b/_freeze/html/rmarkdown/execute-results/html.json @@ -1,7 +1,7 @@ { - "hash": "6c76419cc9da625146c9a0e346502b3c", + "hash": "1d13c61d063e7c3b0cc745b412f1a1ee", "result": { - "markdown": "---\ntitle: \"rmarkdown :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: false\n---\n\n::: {.cell .column-margin}\n\"\"\n

\n

Download PDF

\n\n
\n

Translations (PDF)

\n* Dutch\n* German\n* Italian\n* Japanese\n* Korean\n* Spanish\n* Turkish\n* Vietnamese\n:::\n\n\n## What is rmarkdown?\n\n- **.Rmd files:** Develop your code and ideas side-by-side in a single document. Run code as individual chunks or as an entire document.\n- **Dynamic Documents:** Knit together plots, tables, and results with narrative text. Render to a variety of formats like HTML, PDF, MS Word, or MS PowerPoint.\n- **Reproducible Research:** Upload, link to, or attach your report to share. Anyone can read or run your code to reproduce your work.\n\n## Workflow\n\n1. Open a **new .Rmd file** in the RStudio IDE by going to *File \\> New File \\> R Markdown*.\n\n2. **Embed code** in chunks.\n Run code by line, by chunk, or all at once.\n\n3. **Write text** and add tables, figures, images, and citations.\n Format with Markdown syntax or the RStudio Visual Markdown Editor.\n\n4. **Set output format(s) and options** in the YAML header.\n Customize themes or add parameters to execute or add interactivity with Shiny.\n\n5. **Save and render** the whole document.\n Knit periodically to preview your work as you write.\n\n6. **Share your work!**\n\n### Source Editor\n\n![](images/source-editor.png){fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Source Editor {aria-hidden=\"true\"}\n\n### Features within the Source Editor\n\n1. New File\n2. Embed Code\n3. Write Text\n4. Set Output Format(s) and Options\n5. Save and Render\n6. Share\n\n- Set preview location\n- Insert code chunk\n- Go to code chunk\n- Run code chunk(s)\n- Show outline\n- Modify chunk options\n- Run all previous chunks\n- Run current chunk\n- Switch to visual editor\n:::\n\n### Visual Editor\n\n![](images/rmd-visual-editor.png){fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Visual Editor {aria-hidden=\"true\"}\n\n### Features within the Visual Editor\n\n- Insert citations\n- Style options\n- Add/edit attributes\n- Switch to source editor\n:::\n\n### Rendered Output\n\n![](images/rendered-output.png){fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Rendered Output Window {aria-hidden=\"true\"}\n\n### Features within the Rendered Output Window\n\n- File path to output document\n- Find in document\n- Publish to rpubs.com, shinyapps.io, Posit Connect\n- Reload document\n:::\n\n## Embed Code With knitr\n\n### Code Chunks\n\nSurround code chunks with ```` ```{r} ```` and ```` ``` ```` or use the Insert Code Chunk button.\nAdd a chunk label and/or chunk options inside the curly braces after `r`.\n\n```{{{r chunk-label, include = FALSE}}}\n```\n\n### Set Global Options\n\nSet options for the entire document in the first chunk.\n\n```{{{r include = FALSE}}}\nknitr::opts_chunk$set(message = FALSE)\n```\n\n### Inline Code\n\nInsert `` `r ` `` into text sections.\nCode is evaluated at render and results appear as text.\n\nThe markdown text\n\n``` \nBuilt with `r getRversion()` \n```\n\nwill render as \"Built with 4.3.0\" in the output file.\n\n### Chunk Options\n\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| Option | Default | Effects |\n+==========================+=============+==============================================================================================================+\n| `echo` | `TRUE` | display code in output document |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `error` | `FALSE` | TRUE (display error messages in doc), FALSE (stop render when error occurs) |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `eval` | `TRUE` | run code in chunk |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `include` | `TRUE` | include chunk in doc after running |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `message` | `TRUE` | display code messages in document |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `warning` | `TRUE` | display code warnings in document |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `results` | `\"markup\"` | `\"asis\"` (pass through results), `\"hide\"` (don't display results), `\"hold\"` (put all results below all code) |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `fig.align` | `\"default\"` | `\"left\"`, `\"right\"`, or `\"center\"` |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `fig.alt` | `NULL` | alt text for a figure |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `fig.cap` | `NULL` | figure caption as a character string |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `fig.path` | `\"figure/\"` | prefix for generating file paths |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `fig.width & fig.height` | `7` | plot dimensions in inches |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `out.width` | | rescales output width, e.g. `\"75%\"`, `\"300px\"` |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `collapse` | `FALSE` | collapse all sources & output into a single block |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `comment` | `\"##\"` | prefix for each line of results |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `child` | `NULL` | file(s) to knit and then include |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `purl` | `TRUE` | include or exclude a code chunk when extracting source code with `knitr::purl()` |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n\n: Table of chunk options. The first column is the option name, the second column is the option's default value, the third column describes what the option does.\n\nSee more options and defaults by running `str(knitr::opts_chunk$get())`\n\n## Insert Citations\n\nCreate citations from a bibliography file, a Zotero library, or from DOI references.\n\n### Build Your Bibliography\n\n- Add BibTex or CSL bibliographies to the YAML header.\n\n ``` yaml\n ---\n title: \"My Document\"\n bibliography: references.bib\n link-citations: TRUE\n ---\n ```\n\n- If Zotero is installed locally, your main library will automatically be available.\n\n- Add citations by DOI by searching \"from DOI\" in the **Insert Citation** dialog.\n\n### Insert Citations\n\n- Access the **Insert Citations** dialog in the Visual Editor by clicking the **\\@** symbol in the toolbar or by clicking **Insert \\> Citation.**\n- Add citations with markdown syntax by typing `[@cite]` or `@cite`.\n\n## Insert Tables\n\nOutput data frames as tables using `kable(data, caption)`.\n\n```` \n``` {{r}}\ndata <- faithful[1:4,]\nknitr::kable(data, caption = \"Tables with kable\")\n```\n````\n\nOther table packages include **flextable**, **gt**, and **kableExtra**.\n\n## Write With Markdown\n\nThe syntax on the left renders as the output on the right.\n\n+---------------------------------------------+--------------------------------------------------------------------------+\n| # Markdown Syntax | # Rendered Output |\n| | |\n| ``` | Plain text. |\n| Plain text. | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | End a line with two spaces to |\n| End a line with two spaces to | |\n| start a new paragraph. | start a new paragraph. |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | Also end a line with a backslash |\n| Also end a line with a backslash\\ | |\n| to make a new line. | to make a new line. |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | *italics* and **bold** |\n| *italics* and **bold** | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | superscript^2^ /subscript~2~ |\n| superscript^2^/subscript~2~ | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | ~~strike through~~ |\n| ~~strike through~~ | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | escaped: \\* \\_ \\\\ |\n| escaped: \\* \\_ \\\\ | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | en dash: --, em dash: --- |\n| en dash: --, em dash: --- | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | # Header 1 |\n| # Header 1 | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | ## Header 2 |\n| ## Header 2 | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | ... |\n| ... | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | ###### Header 6 |\n| ###### Header 6 | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | - unordered list |\n| - unordered list | |\n| - item 2 | - item 2 |\n| - item 2a (indent 1 tab) | |\n| - item 2b | - item 2a (indent 1 tab) |\n| ``` | |\n| | - item 2b |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | 1. ordered list |\n| 1. ordered list | |\n| 2. item 2 | 2. item 2 |\n| - item 2a (indent 1 tab) | |\n| - item 2b | - item 2a |\n| ``` | |\n| | - item 2b |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | |\n| | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | [This is a link.](https://posit.co/) |\n| [This is a link.](link url) | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | [This is another link.](https://posit.co/) |\n| [This is another link.][id]. | |\n| | |\n| At the end of the document: | |\n| [id]: link url | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | ![R Markdown logo](images/rmarkdown-logo.png){width=\"300\"} |\n| ![Caption](image.png) | |\n| | |\n| or | |\n| | |\n| ![Caption](id2) | |\n| | |\n| At the end of the document include: | |\n| [id2]: image.png | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | `verbatim code` |\n| `verbatim code` | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ```` | ``` |\n| ``` | multiple lines |\n| multiple lines | of verbatim code |\n| of verbatim code | ``` |\n| ``` | |\n| ```` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | > block quotes |\n| > block quotes | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | equation: $e^{i \\pi} + 1 = 0$ |\n| equation: $e^{i \\pi} + 1 = 0$ | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | equation block: |\n| equation block: | |\n| $$E = mc^{2}$$ | $$ |\n| ``` | E = mc^{2} |\n| | $$ |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | horizontal rule: |\n| horizontal rule: | |\n| --- | ------------------------------------------------------------------------ |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | | Right | Left | Default | Center | |\n| |Right|Left|Default|Center| | |------:|:-----|---------|:------:| |\n| |----:|:---|-------|:----:| | | 12 | 12 | 12 | 12 | |\n| |12 |12 |12 |12 | | | 123 | 123 | 123 | 123 | |\n| |123 |123 |123 |123 | | | 1 | 1 | 1 | 1 | |\n| |1 |1 |1 |1 | | |\n| | : Caption text, example rendered table. |\n| Table: Caption text, example rendered table | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| HTML Tabsets | ::: panel-tabset |\n| | ## Plots |\n| ``` | |\n| ::: panel-tabset | text |\n| ## Plots text | |\n| text | ## Tables |\n| | |\n| ## Tables | more text |\n| more text | ::: |\n| ::: | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n\n: Table of markdown syntax and rendered examples. The syntax in the first column renders to the output in the second column.\n\n\n\n## Set Output Formats and Their Options in YAML\n\nUse the document's YAML header to set an **output format** and customize it with **output options**.\nIndent format 2 characters, indent options 4 characters.\n\n``` yaml\n---\ntitle: \"My Document\"\nauthor: \"Author Name\"\noutput:\n html_document: \n toc: true\n toc-location: left\n---\n```\n\n### Output Format Table\n\n| Output Format | Creates |\n|---------------------------|------------------------------|\n| `html_document` | .html |\n| `pdf_document`[^1] | .pdf |\n| `word_document` | Microsoft Word (.docx) |\n| `powerpoint_presentation` | Microsoft PowerPoint (.pptx) |\n| `odt_document` | OpenDocument Text |\n| `rtf_document` | Rich Text Format |\n| `md_document` | Markdown |\n| `github_document` | Markdown for Github |\n| `ioslides_presentations` | ioslides HTML slides |\n| `slidy_presentation` | Slidy HTML slides |\n| `beamer_presentation`[^2] | Beamer slides |\n\n: Table of output formats. The output format in the first column creates the file type in the second column.\n\n[^1]: PDFs and Beamer slides require LaTeX, use `tinytex::install_tinytex()`.\n\n[^2]: PDFs and Beamer slides require LaTeX, use `tinytex::install_tinytex()`.\n\nAlso see **flexdashboard**, **bookdown**, **distill**, and **blogdown**.\n\n### Output Options Table\n\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| Important Options | Description | HTML | PDF | MS Word | MS PPT |\n+======================+========================================================================================+======+======+=========+========+\n| anchor_sections | Show section anchors on mouse hover (TRUE or FALSE) | X | | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| citation_package | The LaTeX package to process citations (\"default\", \"natbib\", biblatex\") | | | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| code_download | Give readers an option to download the .Rmd source code (TRUE or FALSE) | X | | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| code_folding | Let readers toggle the display of R code (\"none\", \"hide\", or \"show\") | X | | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| css | CSS or SCSS file to use to style the document (e.g. \"style.css\") | X | | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| dev | Graphics device to use for figure output (e.g. \"png\", \"pdf\") | X | X | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| df_print | Method for printing data frames (\"default\", \"kable\", \"tibble\", \"paged\") | X | X | X | X |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| fig_caption | Should figures be rendered with captions (TRUE or FALSE) | X | X | X | X |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| highlight | Syntax highlighting (\"tango\", \"pygments\", \"kate\", \"zenburn\", \"textmate\") | X | X | X | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| includes | File of content to place in doc (\"in_header\", \"before_body\", \"after_body\") | X | X | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| keep_md | Keep the Markdown .md file generated by knitting (TRUE or FALSE) | X | X | X | X |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| keep_tex | Keep the intermediate TEX file used to convert to PDF (TRUE or FALSE) | | X | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| latex_engine | LaTeX engine for producing PDF output (\"pdflatex\", \"xelatex\", or \"lualatex\") | | X | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| reference_docx/\\_doc | docx/pptx file containing styles to copy in the output (e.g. \"file.docx\", \"file.pptx\") | | | X | X |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| theme | Theme options (see Bootswatch and Custom Themes below) | X | | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| toc | Add a table of contents at start of document (TRUE or FALSE) | X | X | X | X |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| toc_depth | The lowest level of headings to add to table of contents (e.g. 2, 3) | X | X | X | X |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| toc_float | Float the table of contents to the left of the main document content (TRUE or FALSE) | X | | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n\n: Table of output options. The first column is the option name, the second column is the description and possible values, and then remaining columns show what file types each option can be applied to.\n\nUse `?` to see all of a format's options, e.g. `?html_document`\n\n## More Header Options\n\n### Parameters\n\nParameterize your documents to ruse with new inputs (e.g. data, values, etc.).\n\n1. **Add parameters** in the header as sub-values of `params`.\n\n ``` yaml\n ---\n params:\n state: \"hawaii\"\n ---\n ```\n\n2. **Call parameters** in code using `params$name`.\n\n ```` \n ``` {{r}}\n data <- df[,params$state]\n summary(data)\n ```\n ````\n\n3. **Set parameters** with Knit with Parameters or the params argument of `render()`.\n\n### Reusable Templates\n\n1. **Create a new package** with an inst/rmarkdown/templates directory.\n\n2. **Add a folder** containing **template.yaml** (below) and **skeleton.Rmd** (template contents).\n\n ``` yaml\n ---\n name: \"My Template\"\n ---\n ```\n\n3. **Install** the package to access template by going to **File \\> New R Markdown \\> From Template**.\n\n### Bootswatch Themes\n\nCustomize HTML documents with Bootswatch themes from the **bslib** package using the theme output option.\nUse `bslib::bootswatch_themes()` to list available themes.\n\n``` yaml\n---\ntitle: \"My Document\"\nauthor: \"Author Name\"\noutput:\n html_document:\n theme:\n bootswatch: solar\n---\n```\n\n### Custom Themes\n\nCustomize individual HTML elements using bslib variables.\nUse `?bs_theme` to see more variables.\n\n``` yaml\n---\noutput:\n html_document:\n theme:\n bg: \"#121212\"\n fg: \"#E4E4E4\"\n base_font:\n google: \"Prompt\"\n---\n```\n\nMore on **bslib** at .\n\n### Styling With CSS and SCSS\n\nAdd CSS and SCSS to your documents by adding a path to a file with the **css** option in the YAML header.\n\n``` yaml\n---\ntitle: \"My Document\"\nauthor: \"Author Name\"\noutput:\n html_document:\n css: \"style.css\"\n---\n```\n\nApply CSS styling by writing HTML tags directly or:\n\n- Use markdown to apply style attributes inline.\n\n - Bracketed Span\\\n `A [green]{.my-color} word.` will render as \"A [green]{style=\"color: green\"} word.\"\n\n - Fenced Div\n\n ``` \n :::{.my-color}\n All of these words\n are green\n :::\n ```\n\n will render as\n\n ::: {style=\"color: green\"}\n All of these words\n\n are green.\n :::\n\n- Use the Visual Editor.\n Go to **Format \\> Div/Span** and add CSS styling directly with Edit Attributes.\n\n### Interactivity\n\nTurn your report into an interactive Shiny document in 4 steps:\n\n1. Add `runtime: shiny` to the YAML header.\n\n ``` yaml\n ---\n output: html_document\n runtime: shiny\n ---\n ```\n\n2. Call Shiny input functions to embed input objects.\n\n3. Call Shiny output functions to embed reactive output.\n\n ```{{{r echo = FALSE}}}\n numericInput(\"n\", \"How many cars?\", 5)\n\n renderTable({\n head(cars, input$n)\n })\n ```\n\n4. Render with `rmarkdown::run()` or click **Run Document** in RStudio IDE.\n\nAlso see Shiny Prerendered for better performance.\n.\n\nEmbed a complete Shiny app into your document with `shiny::shinyAppDir()`.\nMore at .\n\n## Render\n\nWhen you render a document, rmarkdown:\n\n1. Runs the code and embeds results and text into an .md file with knitr.\n2. Converts the .md file into the output format with Pandoc.\n\n**Save,** then **Knit** to preview the document output.\nThe resulting HTML/PDF/MS Word/etc.\ndocument will be created and saved in the same directory as the .Rmd file.\n\nUse `rmarkdown::render()` to render/knit in the R console.\nSee `?render` for available options.\n\n## Share\n\n**Publish on Posit Connect** to share R Markdown documents securely, schedule automatic updates, and interact with parameters in real-time.\n.\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [rmarkdown.rstudio.com](https://rmarkdown.rstudio.com/).\n\nUpdated: 2023-05.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"rmarkdown\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '2.21'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", + "markdown": "---\ntitle: \"rmarkdown :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: false\n---\n\n::: {.cell .column-margin}\n\"Hex\n

\n

Download PDF

\n\"\"/\n
\n

Translations (PDF)

\n* Dutch\n* German\n* Italian\n* Japanese\n* Korean\n* Spanish\n* Turkish\n* Vietnamese\n:::\n\n\n## What is rmarkdown?\n\n- **.Rmd files:** Develop your code and ideas side-by-side in a single document. Run code as individual chunks or as an entire document.\n- **Dynamic Documents:** Knit together plots, tables, and results with narrative text. Render to a variety of formats like HTML, PDF, MS Word, or MS PowerPoint.\n- **Reproducible Research:** Upload, link to, or attach your report to share. Anyone can read or run your code to reproduce your work.\n\n## Workflow\n\n1. Open a **new .Rmd file** in the RStudio IDE by going to *File \\> New File \\> R Markdown*.\n\n2. **Embed code** in chunks.\n Run code by line, by chunk, or all at once.\n\n3. **Write text** and add tables, figures, images, and citations.\n Format with Markdown syntax or the RStudio Visual Markdown Editor.\n\n4. **Set output format(s) and options** in the YAML header.\n Customize themes or add parameters to execute or add interactivity with Shiny.\n\n5. **Save and render** the whole document.\n Knit periodically to preview your work as you write.\n\n6. **Share your work!**\n\n### Source Editor\n\n![](images/source-editor.png){fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Source Editor {aria-hidden=\"true\"}\n\n### Features within the Source Editor\n\n1. New File\n2. Embed Code\n3. Write Text\n4. Set Output Format(s) and Options\n5. Save and Render\n6. Share\n\n- Set preview location\n- Insert code chunk\n- Go to code chunk\n- Run code chunk(s)\n- Show outline\n- Modify chunk options\n- Run all previous chunks\n- Run current chunk\n- Switch to visual editor\n:::\n\n### Visual Editor\n\n![](images/rmd-visual-editor.png){fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Visual Editor {aria-hidden=\"true\"}\n\n### Features within the Visual Editor\n\n- Insert citations\n- Style options\n- Add/edit attributes\n- Switch to source editor\n:::\n\n### Rendered Output\n\n![](images/rendered-output.png){fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Rendered Output Window {aria-hidden=\"true\"}\n\n### Features within the Rendered Output Window\n\n- File path to output document\n- Find in document\n- Publish to rpubs.com, shinyapps.io, Posit Connect\n- Reload document\n:::\n\n## Embed Code With knitr\n\n### Code Chunks\n\nSurround code chunks with ```` ```{r} ```` and ```` ``` ```` or use the Insert Code Chunk button.\nAdd a chunk label and/or chunk options inside the curly braces after `r`.\n\n```{{{r chunk-label, include = FALSE}}}\n```\n\n### Set Global Options\n\nSet options for the entire document in the first chunk.\n\n```{{{r include = FALSE}}}\nknitr::opts_chunk$set(message = FALSE)\n```\n\n### Inline Code\n\nInsert `` `r ` `` into text sections.\nCode is evaluated at render and results appear as text.\n\nThe markdown text\n\n``` \nBuilt with `r getRversion()` \n```\n\nwill render as \"Built with 4.3.0\" in the output file.\n\n### Chunk Options\n\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| Option | Default | Effects |\n+==========================+=============+==============================================================================================================+\n| `echo` | `TRUE` | display code in output document |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `error` | `FALSE` | TRUE (display error messages in doc), FALSE (stop render when error occurs) |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `eval` | `TRUE` | run code in chunk |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `include` | `TRUE` | include chunk in doc after running |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `message` | `TRUE` | display code messages in document |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `warning` | `TRUE` | display code warnings in document |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `results` | `\"markup\"` | `\"asis\"` (pass through results), `\"hide\"` (don't display results), `\"hold\"` (put all results below all code) |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `fig.align` | `\"default\"` | `\"left\"`, `\"right\"`, or `\"center\"` |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `fig.alt` | `NULL` | alt text for a figure |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `fig.cap` | `NULL` | figure caption as a character string |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `fig.path` | `\"figure/\"` | prefix for generating file paths |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `fig.width & fig.height` | `7` | plot dimensions in inches |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `out.width` | | rescales output width, e.g. `\"75%\"`, `\"300px\"` |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `collapse` | `FALSE` | collapse all sources & output into a single block |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `comment` | `\"##\"` | prefix for each line of results |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `child` | `NULL` | file(s) to knit and then include |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n| `purl` | `TRUE` | include or exclude a code chunk when extracting source code with `knitr::purl()` |\n+--------------------------+-------------+--------------------------------------------------------------------------------------------------------------+\n\n: Table of chunk options. The first column is the option name, the second column is the option's default value, the third column describes what the option does.\n\nSee more options and defaults by running `str(knitr::opts_chunk$get())`\n\n## Insert Citations\n\nCreate citations from a bibliography file, a Zotero library, or from DOI references.\n\n### Build Your Bibliography\n\n- Add BibTex or CSL bibliographies to the YAML header.\n\n ``` yaml\n ---\n title: \"My Document\"\n bibliography: references.bib\n link-citations: TRUE\n ---\n ```\n\n- If Zotero is installed locally, your main library will automatically be available.\n\n- Add citations by DOI by searching \"from DOI\" in the **Insert Citation** dialog.\n\n### Insert Citations\n\n- Access the **Insert Citations** dialog in the Visual Editor by clicking the **\\@** symbol in the toolbar or by clicking **Insert \\> Citation.**\n- Add citations with markdown syntax by typing `[@cite]` or `@cite`.\n\n## Insert Tables\n\nOutput data frames as tables using `kable(data, caption)`.\n\n```` \n``` {{r}}\ndata <- faithful[1:4,]\nknitr::kable(data, caption = \"Tables with kable\")\n```\n````\n\nOther table packages include **flextable**, **gt**, and **kableExtra**.\n\n## Write With Markdown\n\nThe syntax on the left renders as the output on the right.\n\n+---------------------------------------------+--------------------------------------------------------------------------+\n| # Markdown Syntax | # Rendered Output |\n| | |\n| ``` | Plain text. |\n| Plain text. | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | End a line with two spaces to |\n| End a line with two spaces to | |\n| start a new paragraph. | start a new paragraph. |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | Also end a line with a backslash |\n| Also end a line with a backslash\\ | |\n| to make a new line. | to make a new line. |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | *italics* and **bold** |\n| *italics* and **bold** | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | superscript^2^ /subscript~2~ |\n| superscript^2^/subscript~2~ | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | ~~strike through~~ |\n| ~~strike through~~ | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | escaped: \\* \\_ \\\\ |\n| escaped: \\* \\_ \\\\ | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | en dash: --, em dash: --- |\n| en dash: --, em dash: --- | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | # Header 1 |\n| # Header 1 | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | ## Header 2 |\n| ## Header 2 | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | ... |\n| ... | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | ###### Header 6 |\n| ###### Header 6 | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | - unordered list |\n| - unordered list | |\n| - item 2 | - item 2 |\n| - item 2a (indent 1 tab) | |\n| - item 2b | - item 2a (indent 1 tab) |\n| ``` | |\n| | - item 2b |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | 1. ordered list |\n| 1. ordered list | |\n| 2. item 2 | 2. item 2 |\n| - item 2a (indent 1 tab) | |\n| - item 2b | - item 2a |\n| ``` | |\n| | - item 2b |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | |\n| | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | [This is a link.](https://posit.co/) |\n| [This is a link.](link url) | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | [This is another link.](https://posit.co/) |\n| [This is another link.][id]. | |\n| | |\n| At the end of the document: | |\n| [id]: link url | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | ![R Markdown logo](images/rmarkdown-logo.png){width=\"300\"} |\n| ![Caption](image.png) | |\n| | |\n| or | |\n| | |\n| ![Caption](id2) | |\n| | |\n| At the end of the document include: | |\n| [id2]: image.png | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | `verbatim code` |\n| `verbatim code` | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ```` | ``` |\n| ``` | multiple lines |\n| multiple lines | of verbatim code |\n| of verbatim code | ``` |\n| ``` | |\n| ```` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | > block quotes |\n| > block quotes | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | equation: $e^{i \\pi} + 1 = 0$ |\n| equation: $e^{i \\pi} + 1 = 0$ | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | equation block: |\n| equation block: | |\n| $$E = mc^{2}$$ | $$ |\n| ``` | E = mc^{2} |\n| | $$ |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | horizontal rule: |\n| horizontal rule: | |\n| --- | ------------------------------------------------------------------------ |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| ``` | | Right | Left | Default | Center | |\n| |Right|Left|Default|Center| | |------:|:-----|---------|:------:| |\n| |----:|:---|-------|:----:| | | 12 | 12 | 12 | 12 | |\n| |12 |12 |12 |12 | | | 123 | 123 | 123 | 123 | |\n| |123 |123 |123 |123 | | | 1 | 1 | 1 | 1 | |\n| |1 |1 |1 |1 | | |\n| | : Caption text, example rendered table. |\n| Table: Caption text, example rendered table | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n| HTML Tabsets | ::: panel-tabset |\n| | ## Plots |\n| ``` | |\n| ::: panel-tabset | text |\n| ## Plots text | |\n| text | ## Tables |\n| | |\n| ## Tables | more text |\n| more text | ::: |\n| ::: | |\n| ``` | |\n+---------------------------------------------+--------------------------------------------------------------------------+\n\n: Table of markdown syntax and rendered examples. The syntax in the first column renders to the output in the second column.\n\n\n\n## Set Output Formats and Their Options in YAML\n\nUse the document's YAML header to set an **output format** and customize it with **output options**.\nIndent format 2 characters, indent options 4 characters.\n\n``` yaml\n---\ntitle: \"My Document\"\nauthor: \"Author Name\"\noutput:\n html_document: \n toc: true\n toc-location: left\n---\n```\n\n### Output Format Table\n\n| Output Format | Creates |\n|---------------------------|------------------------------|\n| `html_document` | .html |\n| `pdf_document`[^1] | .pdf |\n| `word_document` | Microsoft Word (.docx) |\n| `powerpoint_presentation` | Microsoft PowerPoint (.pptx) |\n| `odt_document` | OpenDocument Text |\n| `rtf_document` | Rich Text Format |\n| `md_document` | Markdown |\n| `github_document` | Markdown for Github |\n| `ioslides_presentations` | ioslides HTML slides |\n| `slidy_presentation` | Slidy HTML slides |\n| `beamer_presentation`[^2] | Beamer slides |\n\n: Table of output formats. The output format in the first column creates the file type in the second column.\n\n[^1]: PDFs and Beamer slides require LaTeX, use `tinytex::install_tinytex()`.\n\n[^2]: PDFs and Beamer slides require LaTeX, use `tinytex::install_tinytex()`.\n\nAlso see **flexdashboard**, **bookdown**, **distill**, and **blogdown**.\n\n### Output Options Table\n\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| Important Options | Description | HTML | PDF | MS Word | MS PPT |\n+======================+========================================================================================+======+======+=========+========+\n| anchor_sections | Show section anchors on mouse hover (TRUE or FALSE) | X | | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| citation_package | The LaTeX package to process citations (\"default\", \"natbib\", biblatex\") | | | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| code_download | Give readers an option to download the .Rmd source code (TRUE or FALSE) | X | | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| code_folding | Let readers toggle the display of R code (\"none\", \"hide\", or \"show\") | X | | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| css | CSS or SCSS file to use to style the document (e.g. \"style.css\") | X | | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| dev | Graphics device to use for figure output (e.g. \"png\", \"pdf\") | X | X | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| df_print | Method for printing data frames (\"default\", \"kable\", \"tibble\", \"paged\") | X | X | X | X |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| fig_caption | Should figures be rendered with captions (TRUE or FALSE) | X | X | X | X |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| highlight | Syntax highlighting (\"tango\", \"pygments\", \"kate\", \"zenburn\", \"textmate\") | X | X | X | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| includes | File of content to place in doc (\"in_header\", \"before_body\", \"after_body\") | X | X | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| keep_md | Keep the Markdown .md file generated by knitting (TRUE or FALSE) | X | X | X | X |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| keep_tex | Keep the intermediate TEX file used to convert to PDF (TRUE or FALSE) | | X | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| latex_engine | LaTeX engine for producing PDF output (\"pdflatex\", \"xelatex\", or \"lualatex\") | | X | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| reference_docx/\\_doc | docx/pptx file containing styles to copy in the output (e.g. \"file.docx\", \"file.pptx\") | | | X | X |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| theme | Theme options (see Bootswatch and Custom Themes below) | X | | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| toc | Add a table of contents at start of document (TRUE or FALSE) | X | X | X | X |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| toc_depth | The lowest level of headings to add to table of contents (e.g. 2, 3) | X | X | X | X |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n| toc_float | Float the table of contents to the left of the main document content (TRUE or FALSE) | X | | | |\n+----------------------+----------------------------------------------------------------------------------------+------+------+---------+--------+\n\n: Table of output options. The first column is the option name, the second column is the description and possible values, and then remaining columns show what file types each option can be applied to.\n\nUse `?` to see all of a format's options, e.g. `?html_document`\n\n## More Header Options\n\n### Parameters\n\nParameterize your documents to ruse with new inputs (e.g. data, values, etc.).\n\n1. **Add parameters** in the header as sub-values of `params`.\n\n ``` yaml\n ---\n params:\n state: \"hawaii\"\n ---\n ```\n\n2. **Call parameters** in code using `params$name`.\n\n ```` \n ``` {{r}}\n data <- df[,params$state]\n summary(data)\n ```\n ````\n\n3. **Set parameters** with Knit with Parameters or the params argument of `render()`.\n\n### Reusable Templates\n\n1. **Create a new package** with an inst/rmarkdown/templates directory.\n\n2. **Add a folder** containing **template.yaml** (below) and **skeleton.Rmd** (template contents).\n\n ``` yaml\n ---\n name: \"My Template\"\n ---\n ```\n\n3. **Install** the package to access template by going to **File \\> New R Markdown \\> From Template**.\n\n### Bootswatch Themes\n\nCustomize HTML documents with Bootswatch themes from the **bslib** package using the theme output option.\nUse `bslib::bootswatch_themes()` to list available themes.\n\n``` yaml\n---\ntitle: \"My Document\"\nauthor: \"Author Name\"\noutput:\n html_document:\n theme:\n bootswatch: solar\n---\n```\n\n### Custom Themes\n\nCustomize individual HTML elements using bslib variables.\nUse `?bs_theme` to see more variables.\n\n``` yaml\n---\noutput:\n html_document:\n theme:\n bg: \"#121212\"\n fg: \"#E4E4E4\"\n base_font:\n google: \"Prompt\"\n---\n```\n\nMore on **bslib** at .\n\n### Styling With CSS and SCSS\n\nAdd CSS and SCSS to your documents by adding a path to a file with the **css** option in the YAML header.\n\n``` yaml\n---\ntitle: \"My Document\"\nauthor: \"Author Name\"\noutput:\n html_document:\n css: \"style.css\"\n---\n```\n\nApply CSS styling by writing HTML tags directly or:\n\n- Use markdown to apply style attributes inline.\n\n - Bracketed Span\\\n `A [green]{.my-color} word.` will render as \"A [green]{style=\"color: green\"} word.\"\n\n - Fenced Div\n\n ``` \n :::{.my-color}\n All of these words\n are green\n :::\n ```\n\n will render as\n\n ::: {style=\"color: green\"}\n All of these words\n\n are green.\n :::\n\n- Use the Visual Editor.\n Go to **Format \\> Div/Span** and add CSS styling directly with Edit Attributes.\n\n### Interactivity\n\nTurn your report into an interactive Shiny document in 4 steps:\n\n1. Add `runtime: shiny` to the YAML header.\n\n ``` yaml\n ---\n output: html_document\n runtime: shiny\n ---\n ```\n\n2. Call Shiny input functions to embed input objects.\n\n3. Call Shiny output functions to embed reactive output.\n\n ```{{{r echo = FALSE}}}\n numericInput(\"n\", \"How many cars?\", 5)\n\n renderTable({\n head(cars, input$n)\n })\n ```\n\n4. Render with `rmarkdown::run()` or click **Run Document** in RStudio IDE.\n\nAlso see Shiny Prerendered for better performance.\n.\n\nEmbed a complete Shiny app into your document with `shiny::shinyAppDir()`.\nMore at .\n\n## Render\n\nWhen you render a document, rmarkdown:\n\n1. Runs the code and embeds results and text into an .md file with knitr.\n2. Converts the .md file into the output format with Pandoc.\n\n**Save,** then **Knit** to preview the document output.\nThe resulting HTML/PDF/MS Word/etc.\ndocument will be created and saved in the same directory as the .Rmd file.\n\nUse `rmarkdown::render()` to render/knit in the R console.\nSee `?render` for available options.\n\n## Share\n\n**Publish on Posit Connect** to share R Markdown documents securely, schedule automatic updates, and interact with parameters in real-time.\n.\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [rmarkdown.rstudio.com](https://rmarkdown.rstudio.com/).\n\nUpdated: 2023-06.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"rmarkdown\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '2.21'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", "supporting": [], "filters": [ "rmarkdown/pagebreak.lua" diff --git a/_freeze/html/rstudio-ide/execute-results/html.json b/_freeze/html/rstudio-ide/execute-results/html.json index 30a91aca..2637b951 100644 --- a/_freeze/html/rstudio-ide/execute-results/html.json +++ b/_freeze/html/rstudio-ide/execute-results/html.json @@ -1,7 +1,7 @@ { - "hash": "2629ccbe71a80b46a856d11c7b972669", + "hash": "15b3c67e319a69632c7325a779b22fc5", "result": { - "markdown": "---\ntitle: \"RStudio IDE :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: false\nengine: knitr\n---\n\n::: {.cell .column-margin}\n\"\"\n

\n

Download PDF

\n\n
\n

Translations (PDF)

\n* French\n* Greek\n* Italian\n* Japanese\n* Portuguese\n* Spanish\n:::\n\n\n## Documents and Apps\n\nOpen Shiny, R Markdown, knitr, Sweave, LaTeX, .Rd files and more in Source Pane.\n\n![](images/document-and-apps-rstudio-ide.png){fig-alt=\"RStudio Source Pane view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the RStudio Source Pane {aria-hidden=\"true\"}\n\n### Features within the RStudio Source Pane\n\n- Check spelling\n- Render output\n- Choose output format\n- Configure render options\n- Insert code chunk\n- Publish to server\n- Jump to previous chunk\n- Jump to next chunk\n- Run code\n- Show file outline\n- Visual Editor (reverse side)\n- Jump to section or chunk\n- Run this and all previous code chunks\n- Run this code chunk\n- Set knitr chunk options\n:::\n\nAccess markdown guide at **Help \\> Markdown Quick Reference**.\n\nSee below for more on [Visual Editor].\n\n## Source Editor\n\n![](images/source-editor-rstudio-ide.png){fig-alt=\"RStudio Source Editor view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Source Editor {aria-hidden=\"true\"}\n\n### Features within the Source Editor\n\n- Navigate backwards/forwards\n- Open in new window\n- Save\n- Find and replace\n- Compile as notebook\n- Run selected code\n- Re-run previous code\n- Source with or without Echo or as a Local Job\n- Show file outline\n- Multiple cursors/column selection with Alt + mouse drag.\n- Code diagnostics that appear in the margin. Hover over diagnostic symbols for details.\n- Syntax highlighting based on your file's extension\n- Tab completion to finish function names, file paths, arguments, and more.\n- Multi-language code snippets to quickly use common blocks of code.\n- Jump to function in file\n- Change file type\n- Working Directory\n- Run scripts in separate sessions\n- Maximize, minimize panes\n- Ctrl/Cmd + ↑ to see history\n- R Markdown Build Log\n- Drag pane boundaries\n:::\n\n## Tab Panes\n\n![](images/tab-panes.png){fig-alt=\"RStudio Tab Panes view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Tab Panes {aria-hidden=\"true\"}\n\n### Features within the Tab Panes\n\n- **Import data** with wizard\n- History of past commands to run/copy\n- Manage external databases\n- View memory usage\n- R tutorials\n- Load workspace\n- Save workspace\n- Clear R workspace\n- Search inside environment\n- Choose environment to display from list of parent environments\n- Display objects as list or grid\n- Displays saved objects by type with short description\n- View in data viewer\n- View function source code\n- Create folder\n- Path to displayed directory\n- Delete file\n- Rename file\n- More file options\n- Change directory\n- A File browser keyed to your working directory. Click on file or directory name to open.\n:::\n\n## Version Control\n\nTurn on at **Tools \\> Project Options \\> Git/SVN**\n\n
    \n\n
  • [A]{.git .added} - Added
  • \n\n
  • [D]{.git .deleted} - Deleted
  • \n\n
  • [M]{.git .modified} - Modified
  • \n\n
  • [R]{.git .renamed} - Renamed
  • \n\n
  • [?]{.git .untracked}\n- Untracked
  • \n\n
\n\n![](images/version-control.png){fig-alt=\"Version Control view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the version control view {aria-hidden=\"true\"}\n\n### Features within the version control view\n\n- Stage files\n- Commit staged files\n- Push/Pull to remote\n- View History\n- Current branch\n- Show file diff to view file differences\n:::\n\n## Package Development\n\nCreate a new package with **File \\> New Project \\> New Directory \\> R Package**\n\nEnable roxygen documentation with **Tools \\> Project Options \\> Build Tools**\n\nRoxygen guide at **Help \\> Roxygen Quick Reference**\n\nSee package information in the **Build Tab**\n\n![](images/pd-build-tab.png){fig-alt=\"Package build view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Build Tab {aria-hidden=\"true\"}\n\n### Features within the Build Tab\n\n- Install package and restart R\n- Run devtools::load_all() and reload changes\n- Run R CMD check\n- Clear output and rebuild\n- Customize package build options\n- Run package tests\n:::\n\nRStudio opens plots in a dedicated **Plots** pane\n\n![](images/pd-plots-pane.png){fig-alt=\"Plots view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Plots {aria-hidden=\"true\"}\n\n### Features within the Plots pane\n\n- Navigate recent plots\n- Open in window\n- Export plot\n- Delete plot\n- Delete all plots\n:::\n\nGUI **Package** manager lists every installed package\n\n![](images/pd-package-manager.png){fig-alt=\"Package manager view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Package manager {aria-hidden=\"true\"}\n\n### Features within the Package manager\n\n- Install Packages\n- Update Packages\n- Browse package site\n- Click to load package with `library()`. Unclick to detach package with `detach()`.\n- Package version installed\n- Delete from library\n:::\n\nRStudio opens documentation in a dedicated **Help** pane\n\n![](images/pd-help-pane.png){fig-alt=\"Help pane view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Help pane {aria-hidden=\"true\"}\n\n### Features within the Help pane\n\n- Home page of helpful links\n- Search within help file\n- Search for help file\n:::\n\n**Viewer** pane displays HTML content, such as Shiny apps, R Markdown reports, and interactive visualizations\n\n![](images/pd-viewer-pane.png){fig-alt=\"Viewer pane view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Viewer pane {aria-hidden=\"true\"}\n\n### Features within the Viewer pane\n\n- Stop Shiny apps\n- Publish to shinyapps.io, rpubs, Posit Connect, ...\n- Refresh\n:::\n\n`View()` opens spreadsheet like view of data set\n\n![](images/pd-view-data.png){fig-alt=\"Spreadsheet pane view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the data set spreadsheet {aria-hidden=\"true\"}\n\n### Features within the data set spreadsheet\n\n- Filter rows by value or value range\n- Sort by values\n- Search for value\n:::\n\n## Debug Mode\n\nUse `debug()`, `browser()`, or a breakpoint and execute your code to open the debugger mode.\n\n![](images/dm-console.png){fig-alt=\"Debug console view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the debug console {aria-hidden=\"true\"}\n\n### Features within the debug console\n\n- Launch debugger mode from origin of error\n- Open traceback to examine the functions that R called before the error occurred\n- Click next to line number to add/remove a breakpoint.\n- Highlighted line shows where execution has paused\n- Run commands in environment where execution has paused\n- Examine variables in executing environment\n- Select function in traceback to debug\n- Step through code one line at a time\n- Step into and out of functions to run\n- Resume execution\n- Quit debug mode\n:::\n\n## Keyboard Shortcuts\n\nView the Keyboard Shortcut Quick Reference with **Tools \\> Keyboard Shortcuts** or Alt/Option + Shift + K\n\n![](images/tools-keyboard-shortcuts.png){fig-alt=\"Keyboard Shortcut Quick Reference view\" fig-align=\"center\"}\n\nSearch for keyboard shortcuts with **Tools \\> Show Command Palette** or Ctrl/Cmd + Shift + P.\n\n![](images/tools-show-command-palette.png){fig-alt=\"Show Command Palette view\" fig-align=\"center\"}\n\n## Visual Editor\n\n![](images/ide-visual-editor.png){fig-alt=\"Visual Editor view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Visual Editor {aria-hidden=\"true\"}\n\n### Features within the Visual Editor\n\n- Check spelling\n- Render output\n- Choose output format\n- Choose output location\n- Insert code chunk\n- Jump to previous chunk\n- Jump to next chunk\n- Run selected lines\n- Publish to server\n- Show file outline\n- Block format\n- Back to Source Editor (front page)\n- Insert verbatim code\n- Clear formatting\n- Lists and block quotes\n- Links\n- Citations\n- Images\n- More formatting\n- Insert blocks, citations, equations, and special characters\n- Insert and edit tables\n- File outline\n- Add/Edit attributes\n- Jump to chunk or header\n- Set knitr chunk options\n- Run this and all previous code chunks\n- Run this code chunk\n:::\n\n## RStudio Workbench\n\n### Why RStudio Workbench?\n\nExtend the open source server with a commercial license, support, and more:\n\n- open and run multiple R sessions at once\n- tune your resources to improve performance\n- administrative tools for managing user sessions\n- collaborate real-time with others in shared projects\n- switch easily from one version of R to a different version\n- integrate with your authentication, authorization, and audit practices\n- work in the RStudio IDE, JupyterLab, Jupyter Notebooks, or VS Code\n\nDownload a free [45 day evaluation](https://posit.co/products/enterprise/workbench/).\n\n## Share Projects\n\n**File \\> New Project**\n\nRStudio saves the call history, workspace, and working directory associated with a project.\nIt reloads each when you re-open a project.\n\n![](images/share-projects.png){fig-alt=\"Share Project view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Share Project {aria-hidden=\"true\"}\n\n### Features within the Share Project\n\n- Start **new R Session** in current project\n- Close R Session in project\n- Active shared collaborators\n- Name of current project\n- **Share Project** with Collaborators\n- **Select R Version**\n:::\n\n## Run Remote Jobs\n\nRun R on remote clusters (Kubernetes/Slurm) via the Job Launcher\n\n![](images/run-remote-job.png){fig-alt=\"Launcher view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Job Launcher {aria-hidden=\"true\"}\n\n### Features within the Job Launcher\n\n- Launch a job\n- Monitor launcher jobs\n- Run launcher jobs remotely\n:::\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [docs.posit.co/ide/user](https://docs.posit.co/ide/user/).\n\nUpdated: 2023-05.\n\nRStudio IDE 2023.3.0.386.\n\n------------------------------------------------------------------------\n", + "markdown": "---\ntitle: \"RStudio IDE :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: false\nengine: knitr\n---\n\n::: {.cell .column-margin}\n\"Hex\n

\n

Download PDF

\n\"\"/\n
\n

Translations (PDF)

\n* French\n* Greek\n* Italian\n* Japanese\n* Portuguese\n* Spanish\n:::\n\n\n## Documents and Apps\n\nOpen Shiny, R Markdown, knitr, Sweave, LaTeX, .Rd files and more in Source Pane.\n\n![](images/document-and-apps-rstudio-ide.png){fig-alt=\"RStudio Source Pane view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the RStudio Source Pane {aria-hidden=\"true\"}\n\n### Features within the RStudio Source Pane\n\n- Check spelling\n- Render output\n- Choose output format\n- Configure render options\n- Insert code chunk\n- Publish to server\n- Jump to previous chunk\n- Jump to next chunk\n- Run code\n- Show file outline\n- Visual Editor (reverse side)\n- Jump to section or chunk\n- Run this and all previous code chunks\n- Run this code chunk\n- Set knitr chunk options\n:::\n\nAccess markdown guide at **Help \\> Markdown Quick Reference**.\n\nSee below for more on [Visual Editor].\n\n## Source Editor\n\n![](images/source-editor-rstudio-ide.png){fig-alt=\"RStudio Source Editor view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Source Editor {aria-hidden=\"true\"}\n\n### Features within the Source Editor\n\n- Navigate backwards/forwards\n- Open in new window\n- Save\n- Find and replace\n- Compile as notebook\n- Run selected code\n- Re-run previous code\n- Source with or without Echo or as a Local Job\n- Show file outline\n- Multiple cursors/column selection with Alt + mouse drag.\n- Code diagnostics that appear in the margin. Hover over diagnostic symbols for details.\n- Syntax highlighting based on your file's extension\n- Tab completion to finish function names, file paths, arguments, and more.\n- Multi-language code snippets to quickly use common blocks of code.\n- Jump to function in file\n- Change file type\n- Working Directory\n- Run scripts in separate sessions\n- Maximize, minimize panes\n- Ctrl/Cmd + ↑ to see history\n- R Markdown Build Log\n- Drag pane boundaries\n:::\n\n## Tab Panes\n\n![](images/tab-panes.png){fig-alt=\"RStudio Tab Panes view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Tab Panes {aria-hidden=\"true\"}\n\n### Features within the Tab Panes\n\n- **Import data** with wizard\n- History of past commands to run/copy\n- Manage external databases\n- View memory usage\n- R tutorials\n- Load workspace\n- Save workspace\n- Clear R workspace\n- Search inside environment\n- Choose environment to display from list of parent environments\n- Display objects as list or grid\n- Displays saved objects by type with short description\n- View in data viewer\n- View function source code\n- Create folder\n- Path to displayed directory\n- Delete file\n- Rename file\n- More file options\n- Change directory\n- A File browser keyed to your working directory. Click on file or directory name to open.\n:::\n\n## Version Control\n\nTurn on at **Tools \\> Project Options \\> Git/SVN**\n\n
    \n\n
  • [A]{.git .added} - Added
  • \n\n
  • [D]{.git .deleted} - Deleted
  • \n\n
  • [M]{.git .modified} - Modified
  • \n\n
  • [R]{.git .renamed} - Renamed
  • \n\n
  • [?]{.git .untracked}\n- Untracked
  • \n\n
\n\n![](images/version-control.png){fig-alt=\"Version Control view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the version control view {aria-hidden=\"true\"}\n\n### Features within the version control view\n\n- Stage files\n- Commit staged files\n- Push/Pull to remote\n- View History\n- Current branch\n- Show file diff to view file differences\n:::\n\n## Package Development\n\nCreate a new package with **File \\> New Project \\> New Directory \\> R Package**\n\nEnable roxygen documentation with **Tools \\> Project Options \\> Build Tools**\n\nRoxygen guide at **Help \\> Roxygen Quick Reference**\n\nSee package information in the **Build Tab**\n\n![](images/pd-build-tab.png){fig-alt=\"Package build view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Build Tab {aria-hidden=\"true\"}\n\n### Features within the Build Tab\n\n- Install package and restart R\n- Run devtools::load_all() and reload changes\n- Run R CMD check\n- Clear output and rebuild\n- Customize package build options\n- Run package tests\n:::\n\nRStudio opens plots in a dedicated **Plots** pane\n\n![](images/pd-plots-pane.png){fig-alt=\"Plots view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Plots {aria-hidden=\"true\"}\n\n### Features within the Plots pane\n\n- Navigate recent plots\n- Open in window\n- Export plot\n- Delete plot\n- Delete all plots\n:::\n\nGUI **Package** manager lists every installed package\n\n![](images/pd-package-manager.png){fig-alt=\"Package manager view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Package manager {aria-hidden=\"true\"}\n\n### Features within the Package manager\n\n- Install Packages\n- Update Packages\n- Browse package site\n- Click to load package with `library()`. Unclick to detach package with `detach()`.\n- Package version installed\n- Delete from library\n:::\n\nRStudio opens documentation in a dedicated **Help** pane\n\n![](images/pd-help-pane.png){fig-alt=\"Help pane view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Help pane {aria-hidden=\"true\"}\n\n### Features within the Help pane\n\n- Home page of helpful links\n- Search within help file\n- Search for help file\n:::\n\n**Viewer** pane displays HTML content, such as Shiny apps, R Markdown reports, and interactive visualizations\n\n![](images/pd-viewer-pane.png){fig-alt=\"Viewer pane view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Viewer pane {aria-hidden=\"true\"}\n\n### Features within the Viewer pane\n\n- Stop Shiny apps\n- Publish to shinyapps.io, rpubs, Posit Connect, ...\n- Refresh\n:::\n\n`View()` opens spreadsheet like view of data set\n\n![](images/pd-view-data.png){fig-alt=\"Spreadsheet pane view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the data set spreadsheet {aria-hidden=\"true\"}\n\n### Features within the data set spreadsheet\n\n- Filter rows by value or value range\n- Sort by values\n- Search for value\n:::\n\n## Debug Mode\n\nUse `debug()`, `browser()`, or a breakpoint and execute your code to open the debugger mode.\n\n![](images/dm-console.png){fig-alt=\"Debug console view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the debug console {aria-hidden=\"true\"}\n\n### Features within the debug console\n\n- Launch debugger mode from origin of error\n- Open traceback to examine the functions that R called before the error occurred\n- Click next to line number to add/remove a breakpoint.\n- Highlighted line shows where execution has paused\n- Run commands in environment where execution has paused\n- Examine variables in executing environment\n- Select function in traceback to debug\n- Step through code one line at a time\n- Step into and out of functions to run\n- Resume execution\n- Quit debug mode\n:::\n\n## Keyboard Shortcuts\n\nView the Keyboard Shortcut Quick Reference with **Tools \\> Keyboard Shortcuts** or Alt/Option + Shift + K\n\n![](images/tools-keyboard-shortcuts.png){fig-alt=\"Keyboard Shortcut Quick Reference view\" fig-align=\"center\"}\n\nSearch for keyboard shortcuts with **Tools \\> Show Command Palette** or Ctrl/Cmd + Shift + P.\n\n![](images/tools-show-command-palette.png){fig-alt=\"Show Command Palette view\" fig-align=\"center\"}\n\n## Visual Editor\n\n![](images/ide-visual-editor.png){fig-alt=\"Visual Editor view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Visual Editor {aria-hidden=\"true\"}\n\n### Features within the Visual Editor\n\n- Check spelling\n- Render output\n- Choose output format\n- Choose output location\n- Insert code chunk\n- Jump to previous chunk\n- Jump to next chunk\n- Run selected lines\n- Publish to server\n- Show file outline\n- Block format\n- Back to Source Editor (front page)\n- Insert verbatim code\n- Clear formatting\n- Lists and block quotes\n- Links\n- Citations\n- Images\n- More formatting\n- Insert blocks, citations, equations, and special characters\n- Insert and edit tables\n- File outline\n- Add/Edit attributes\n- Jump to chunk or header\n- Set knitr chunk options\n- Run this and all previous code chunks\n- Run this code chunk\n:::\n\n## RStudio Workbench\n\n### Why RStudio Workbench?\n\nExtend the open source server with a commercial license, support, and more:\n\n- open and run multiple R sessions at once\n- tune your resources to improve performance\n- administrative tools for managing user sessions\n- collaborate real-time with others in shared projects\n- switch easily from one version of R to a different version\n- integrate with your authentication, authorization, and audit practices\n- work in the RStudio IDE, JupyterLab, Jupyter Notebooks, or VS Code\n\nDownload a free [45 day evaluation](https://posit.co/products/enterprise/workbench/).\n\n## Share Projects\n\n**File \\> New Project**\n\nRStudio saves the call history, workspace, and working directory associated with a project.\nIt reloads each when you re-open a project.\n\n![](images/share-projects.png){fig-alt=\"Share Project view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Share Project {aria-hidden=\"true\"}\n\n### Features within the Share Project\n\n- Start **new R Session** in current project\n- Close R Session in project\n- Active shared collaborators\n- Name of current project\n- **Share Project** with Collaborators\n- **Select R Version**\n:::\n\n## Run Remote Jobs\n\nRun R on remote clusters (Kubernetes/Slurm) via the Job Launcher\n\n![](images/run-remote-job.png){fig-alt=\"Launcher view\" fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the features in the Job Launcher {aria-hidden=\"true\"}\n\n### Features within the Job Launcher\n\n- Launch a job\n- Monitor launcher jobs\n- Run launcher jobs remotely\n:::\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [docs.posit.co/ide/user](https://docs.posit.co/ide/user/).\n\nUpdated: 2023-06.\n\nRStudio IDE 2023.3.0.386.\n\n------------------------------------------------------------------------\n", "supporting": [], "filters": [ "rmarkdown/pagebreak.lua" diff --git a/_freeze/html/shiny/execute-results/html.json b/_freeze/html/shiny/execute-results/html.json index abbc8f28..4793b531 100644 --- a/_freeze/html/shiny/execute-results/html.json +++ b/_freeze/html/shiny/execute-results/html.json @@ -1,7 +1,7 @@ { - "hash": "a203c642eba116d4119d844e145849ad", + "hash": "5a1b923cc6dde17dc8ce3ea858084522", "result": { - "markdown": "---\ntitle: \"Shiny :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: true\n---\n\n::: {.cell .column-margin}\n\"\"\n

\n

Download PDF

\n\n
\n

Translations (PDF)

\n* French\n* German\n* Spanish\n* Turkish\n* Vietnamese\n:::\n\n\n## Building an App\n\nA **Shiny** app is a web page (`ui`) connected to a computer running a live R session (`server`).\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(shiny)\n```\n:::\n\n\nUsers can manipulate the UI, which will cause the server to update the UI's display (by running R code).\n\nSave your template as `app.R`.\nKeep your app in a directory along with optional extra files.\n\n**app-name:** The directory name is the app name\n\n- **app.R**\n\n- DESCRIPTION and README: (optional) used in showcase mode\n\n- R/: (optional) directory of supplemental .R files that are sources automatically, must be named `R`\n\n- www/: (optional) directory of giles to share with web browsers (images, CSS, .js, etc.), must be named `www`\n\nLaunch apps stored in a directory with `runApp()`.\n\nTo generate the template, type `shinyApp` and press `Tab` in the RStudio IDE or go to **File \\> New Project \\> New Directory \\> Shiny Web Applications**.\n\n\n::: {.cell}\n\n```{.r .cell-code}\n# app.R \nlibrary(shiny)\n\n#In ui nest R functions to build an HTML interface\nui <- fluidPage(\n numericInput(inputId = \"n\", \"Sample size\", value = 25),\n plotOutput(outputId = \"hist\")\n)\n# Customize the UI with Layout Functions\n# Add Inputs with *Input() functions\n# Add Outputs with *Output() functions\n\n\n# Tell the server how to render outputs and respond to inputs with R\nserver <- function(input, output, session) {\n output$hist <- renderPlot({\n hist(rnorm(input$n))\n })\n}\n# Wrap code in render*() functions before saving to output\n# Refer to UI inputs with input$ and outputs with output$\n \n# Call shinyApp() to combine ui and server into an interactive app!\nshinyApp(ui = ui, server = server)\n```\n:::\n\n\nSee annotated examples of Shiny apps by running `runExample()`.\nRun `runExample()` with no arguments for a list of example names.\n\n## Share\n\nShare your app in three ways:\n\n1. Host it on [shinyapps.io](shinyapps.io), a cloud based service from Posit. To deploy Shiny apps:\n - Create a free or professional account at [shinyapps.io](shinyapps.io)\n\n - Click the Publish icon in RStudio IDE, or run: `rsconnect::deployApp(\"\")`\n2. Purchase Posit Connect, a publishing platform for R and Python. [posit.co/products/enterprise/connect/](posit.co/products/enterprise/connect/)\n3. Build your own Shiny Server. [posit.co/products/open-source/shinyserver/](posit.co/products/open-source/shinyserver/)\n\n## Outputs\n\n`render*()` and `*Output()` functions work together to add R output to the UI.\n\n+----------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------+\n| `render*()` Functions | `*Output()` Functions |\n+==================================================================================================================================+===============================================================================+\n| `DT::renderDataTable(expr, options, searchDelay, callback, escape, env, quoted, outputArgs)` | `dataTableOutput(outputId)` |\n+----------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------+\n| `renderImage(expr, env, quoted, deleteFile, outputArgs)` | `imageOutput(outputId, width, height, click, dblclick, hover, brush, inline)` |\n+----------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------+\n| `renderPlot(expr, width, height, res, …, alt, env, quoted, execOnResixe, outputArgs` | `plotOutput(outputId, width, height, click, dblclick, hover, brush, inline)` |\n+----------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------+\n| `renderPrint(expr, env, quoted, width, outputArgs)` | `verbatimTextOutput(outputId, placeholder)` |\n+----------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------+\n| `renderTable(expr, striped, hover, bordered, spacing, width, align, rownames, colnames, digits, na, …, env, quoted, outputArgs)` | `tableOutput(outputId)` |\n+----------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------+\n| `renderText(expr, env, quoted, outputArgs, sep)` | `textOutput(outputId, container, inline)` |\n+----------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------+\n| `renderUI(expr, env, quoted, outputArgs)` | `uiOutput(outputId, inline, container, …)`\\ |\n| | `htmlOutput(outputId, inline, container, …)` |\n+----------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------+\n\n: Table of render\\*() functions and their associated \\*Output() functions.\n\nThese are the core output types.\nSee [htmlwidgets.org](htmlwidgets.org) for many more options.\n\n## Inputs\n\nCollect values from the user.\n\nAccess the current value of an input object with `input$`.\nInput values are **reactive**.\n\n- `actionButton(inputId, label, icon, width, ...)`\n\n- `actionLink(inputId, label, icon, ...)`\n\n- `checkboxGroupInput(inputId, label, choices, selected, inline, width, choiceNames, choiceValues)`\n\n- `checkboxInput(inputId, label, value, width)`\n\n- `dateInput(inputId, label, value, min, max, format, startview, weekstart, language, width, autoclose, datesdisabled, daysofweekdisabled)`\n\n- `dateRangeInput(inputId, label, start, end, min, max, format, startview, weekstart, language, separator, width, autoclose)`\n\n- `fileInput(inputId, label, multiple, accept, width, buttonLabel, placeholder)`\n\n- `numericInput(inputId, label, value, min, max, step, width)`\n\n- `passwordInput(inputId, label, value, width, placeholder)`\n\n- `radioButtons(inputId, label, choices, selected, inline, width, choiceNames, choiceValues)`\n\n- `selectInput(inputId, label, choices, selected, multiple, selectize, width, size)`: Also `selectizeInput()`\n\n- `sliderInput(inputId, label, min, max, value, step, round, format, locale, ticks, animate, width, sep, pre, post, timeFormat, timezone, dragRange)`\n\n- `submitButton(text, icon, width)`: Prevent reactions for entire app\n\n- `textInput(inputId, label, value, width, placeholder)`: Also `textAreaInput()`\n\n\n\n## Reactivity\n\nReactive values work together with reactive functions.\nCall a reactive value from within the arguments of one of these functions to avoid the error.\n**Operation not allowed without an active reactive context.**\n\n![](images/reactivity-diagram.png){fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the reactivity diagram {aria-hidden=\"true\"}\n\n### Phases in the reactivity diagram\n\n- Create your own reactive values\n - `reactiveValues()`\n - `reactiveFileReader()`\n - `reactivePoll()`\n - `*Input()`\n- Perform side effects\n - `observeEvent()`\n\n - `observe()`\n- Schedule updates\n - `invalidateLater()`\n- Create reactive expressions\n - `reactive()`\n- Remove reactivity\n - `isolate()`\n- React based on event\n - `eventReactive()`\n- Render reactive output\n - `render*()`\n:::\n\n### Create Your own Reactive Values\n\n- `*Input()` functions: (see front page) Each input function creates a reactive value stored as input\\$.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n # *Input() example\n ui <- fluidPage(\n textInput(\"a\",\"\",\"A\")\n )\n ```\n :::\n\n\n- `reactiveValues(...)`: Creates a list of reactive values whose values you can set.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n #reactiveValues example\n server <- function(input,output){\n rv <- reactiveValues() \n rv$number <- 5\n }\n ```\n :::\n\n\n### Create Reactive Expressions\n\n- `reactive(x, env, quoted, label, domain)`:\n\n - Reactive expressions:\n\n - cache their value to reduce computation\n\n - can be called elsewhere\n\n - notify dependencies when invalidated\n\n Call the expression with function sytrax, e.g. `re()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n library(shiny)\n \n ui <- fluidPage(\n textInput(\"a\",\"\",\"A\"), \n textInput(\"z\",\"\",\"Z\"), \n textOutput(\"b\"))\n \n server <- function(input,output){\n re <- reactive({ \n paste(input$a,input$z)})\n output$b <- renderText({\n re()\n }) \n }\n \n shinyApp(ui, server)\n ```\n :::\n\n\n### React Based on Event\n\n- `eventReactive(eventExpr, valueExpr, event.env, event.quoted, value.env, value.quoted, ..., label, domain, ignoreNULL, ignoreInit)`: Creates reactive expression with code in 2nd argument that only invalidates when reactive values in 1st argument change.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n library(shiny)\n \n ui <- fluidPage(\n textInput(\"a\",\"\",\"A\"), \n actionButton(\"go\",\"Go\"), \n textOutput(\"b\")\n )\n \n server <- function(input,output){\n re <- eventReactive(\n input$go,{input$a})\n output$b <- renderText({\n re()\n }) \n }\n ```\n :::\n\n\n### Render Reactive Output\n\n- `render*()` functions: (see front page) Builds an object to display.\n Will rerun code in body to rebuild the object whenever a reactive value in the code changes.\n Save the results to `output$`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n library(shiny)\n \n ui <- fluidPage(\n textInput(\"a\",\"\",\"A\"), \n textOutput(\"b\")\n )\n \n server <- function(input,output){\n output$b <-\n renderText({\n input$a\n })\n }\n \n shinyApp(ui, server)\n ```\n :::\n\n\n### Perform Side Effects\n\n- `observeEvent(eventExpr, handlerExpr, event.env, event.quoted, handler.env, handler.quoted, ..., label, suspended, priority, domain, autoDestroy, ignoreNULL, ignoreInit, once)`: Runs code in 2nd argument when reactive values in 1st argument change.\n See `observe()` for alternative.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n library(shiny)\n \n ui <- fluidPage(textInput(\"a\",\"\",\"A\"), actionButton(\"go\",\"Go\"))\n \n server <- function(input,output){\n observeEvent(input$go, {\n print(input$a)\n })\n }\n \n shinyApp(ui, server)\n ```\n :::\n\n\n### Remove Reactivity\n\n- `isolate(expr)`: Runs a code block.\n Returns a **non-reactive** copy of the results.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n library(shiny)\n \n ui <- fluidPage(\n textInput(\"a\",\"\",\"A\"), \n textOutput(\"b\")\n )\n \n server <- function(input,output){ \n output$b <- \n renderText({\n isolate({input$a})\n })\n }\n \n shinyApp(ui, server)\n ```\n :::\n\n\n## UI\n\nAn app's UI is an HTML document.\n\nUse Shiny's functions to assemble this HTML with R.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nfluidPage(\n textInput(\"a\",\"\")\n)\n```\n:::\n\n\nReturns HTML:\n\n``` html\n
\n
\n \n \n
\n
\n```\n\nAdd static HTML elements with **tags**, a list of functions that parallel common HTML tags, e.g. `tags$a()`.\nUnnamed arguments will be passed into the tag; named arguments will become tag attributes.\n\nRun `names(tags)` for a complete list.\n`tags$h1(\"Header\")` -\\> `

Header

`\n\nThe most common tags have wrapper functions.\nYou do not need to prefix their names with `tags$`.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nui <- fluidPage(\n h1(\"Header 1\"), #

Header 1

\n hr(), #
\n br(), #
\n p(strong(\"bold\")), #

bold

\n p(em(\"italic\")), #

italic

\n p(code(\"code\")), #

code

\n a(href=\"\", \"link\"), # link\n HTML(\"

Raw html

\") # display raw html\n)\n```\n:::\n\n\nTo include a CSS file, use `includeCSS()`, or\n\n1. Place the file in the `www` subdirectory\n\n2. Link to it with:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n tags$head(tags$link(rel = \"stylesheet\", \n type = \"text/css\", \n href = \"\"))\n ```\n :::\n\n\nTo include JavaScript, use `includeScript()`, or\n\n1. Place the file in the `www` subdirectory\n\n2. Link to it with:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n tags$head(tags$script(src = \"\"))\n ```\n :::\n\n\nTo include an image:\n\n1. Place the file in the `www` subdirectory\n\n2. Link to it with:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n img(src = \"\")\n ```\n :::\n\n\n## Layouts\n\nCombine multiple elements into a \"single element\" that has its own properties with a panel function, e.g.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nwellPanel(\n dateInput(\"a\", \"\"),\n submitButton()\n)\n```\n:::\n\n\nOther elements:\n\n- `absolutePanel()`\n- `conditionalPanel()`\n- `fixedPanel()`\n- `headerPanel()`\n- `inputPanel()`\n- `mainPanel()`\n- `navlistPanel()`\n- `sidebarPanel()`\n- `tabPanel()`\n- `tabsetPanel()`\n- `titlePanel()`\n- `wellPanel()`\n\nOrganize panels and elements into a layout with a layour function.\nAdd elements as arguments of the layout functions.\n\n- `sidebarLayout()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n ui <- fluidPage(\n sidebarLayout(\n sidebarPanel(),\n mainPanel()\n )\n )\n ```\n :::\n\n\n- `fluidRow()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n ui <- fluidPage(\n fluidRow(column(width = 4),\n column(width = 2, offset = 3)),\n fluidRow(column(width = 12))\n )\n ```\n :::\n\n\nAlso `flowLayout()`, `splitLayout()`, `verticalLayout()`, `fixedPage()`, and `fixedRow()`.\n\nLayer tabPanels on top of each other, and navigate between them with:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nui <- fluidPage(\n tabsetPanel(\n tabPanel(\"tab1\", \"contents\"),\n tabPanel(\"tab2\", \"contents\"),\n tabPanel(\"tab3\", \"contents\")\n )\n)\n```\n:::\n\n::: {.cell}\n\n```{.r .cell-code}\nui <- fluidPage(\n navlistPanel(\n tabPanel(\"tab1\", \"contents\"),\n tabPanel(\"tab2\", \"contents\"),\n tabPanel(\"tab3\", \"contents\")\n )\n)\n```\n:::\n\n::: {.cell}\n\n```{.r .cell-code}\nui <- navbarPage(\n title = \"Page\",\n tabPanel(\"tab1\", \"contents\"),\n tabPanel(\"tab2\", \"contents\"),\n tabPanel(\"tab3\", \"contents\")\n)\n```\n:::\n\n\n## Themes\n\nUse the **bslib** pacage to add existing themes to your Shiny app ui, or make your own.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(bslib)\nui <- fluidPage(\n theme = bs_theme(\n boothswatch = \"darkly\",\n ...\n )\n)\n```\n:::\n\n\n- `bootswatch_themes()`: Get a list of themes.\n\nBuild your own theme by customizing individual arguments.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nbs_theme(bg = \"#558AC5\",\n fg = \"#F9B02D\",\n ...)\n```\n:::\n\n\n- `?bs_theme` for a full list of arguments.\n\n- `bs_themer()`: Place within the server function ot use the interactive theming widget.\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [shiny.rstudio.com](https://shiny.rstudio.com/)\n\nUpdated: 2023-05.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"shiny\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.7.4'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", + "markdown": "---\ntitle: \"Shiny :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: true\n---\n\n::: {.cell .column-margin}\n\"Hex\n

\n

Download PDF

\n\"\"/\n
\n

Translations (PDF)

\n* French\n* German\n* Spanish\n* Turkish\n* Vietnamese\n:::\n\n\n## Building an App\n\nA **Shiny** app is a web page (`ui`) connected to a computer running a live R session (`server`).\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(shiny)\n```\n:::\n\n\nUsers can manipulate the UI, which will cause the server to update the UI's display (by running R code).\n\nSave your template as `app.R`.\nKeep your app in a directory along with optional extra files.\n\n**app-name:** The directory name is the app name\n\n- **app.R**\n\n- DESCRIPTION and README: (optional) used in showcase mode\n\n- R/: (optional) directory of supplemental .R files that are sources automatically, must be named `R`\n\n- www/: (optional) directory of giles to share with web browsers (images, CSS, .js, etc.), must be named `www`\n\nLaunch apps stored in a directory with `runApp()`.\n\nTo generate the template, type `shinyApp` and press `Tab` in the RStudio IDE or go to **File \\> New Project \\> New Directory \\> Shiny Web Applications**.\n\n\n::: {.cell}\n\n```{.r .cell-code}\n# app.R \nlibrary(shiny)\n\n#In ui nest R functions to build an HTML interface\nui <- fluidPage(\n numericInput(inputId = \"n\", \"Sample size\", value = 25),\n plotOutput(outputId = \"hist\")\n)\n# Customize the UI with Layout Functions\n# Add Inputs with *Input() functions\n# Add Outputs with *Output() functions\n\n\n# Tell the server how to render outputs and respond to inputs with R\nserver <- function(input, output, session) {\n output$hist <- renderPlot({\n hist(rnorm(input$n))\n })\n}\n# Wrap code in render*() functions before saving to output\n# Refer to UI inputs with input$ and outputs with output$\n \n# Call shinyApp() to combine ui and server into an interactive app!\nshinyApp(ui = ui, server = server)\n```\n:::\n\n\nSee annotated examples of Shiny apps by running `runExample()`.\nRun `runExample()` with no arguments for a list of example names.\n\n## Share\n\nShare your app in three ways:\n\n1. Host it on [shinyapps.io](shinyapps.io), a cloud based service from Posit. To deploy Shiny apps:\n - Create a free or professional account at [shinyapps.io](shinyapps.io)\n\n - Click the Publish icon in RStudio IDE, or run: `rsconnect::deployApp(\"\")`\n2. Purchase Posit Connect, a publishing platform for R and Python. [posit.co/products/enterprise/connect/](posit.co/products/enterprise/connect/)\n3. Build your own Shiny Server. [posit.co/products/open-source/shinyserver/](posit.co/products/open-source/shinyserver/)\n\n## Outputs\n\n`render*()` and `*Output()` functions work together to add R output to the UI.\n\n+----------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------+\n| `render*()` Functions | `*Output()` Functions |\n+==================================================================================================================================+===============================================================================+\n| `DT::renderDataTable(expr, options, searchDelay, callback, escape, env, quoted, outputArgs)` | `dataTableOutput(outputId)` |\n+----------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------+\n| `renderImage(expr, env, quoted, deleteFile, outputArgs)` | `imageOutput(outputId, width, height, click, dblclick, hover, brush, inline)` |\n+----------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------+\n| `renderPlot(expr, width, height, res, …, alt, env, quoted, execOnResixe, outputArgs` | `plotOutput(outputId, width, height, click, dblclick, hover, brush, inline)` |\n+----------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------+\n| `renderPrint(expr, env, quoted, width, outputArgs)` | `verbatimTextOutput(outputId, placeholder)` |\n+----------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------+\n| `renderTable(expr, striped, hover, bordered, spacing, width, align, rownames, colnames, digits, na, …, env, quoted, outputArgs)` | `tableOutput(outputId)` |\n+----------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------+\n| `renderText(expr, env, quoted, outputArgs, sep)` | `textOutput(outputId, container, inline)` |\n+----------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------+\n| `renderUI(expr, env, quoted, outputArgs)` | `uiOutput(outputId, inline, container, …)`\\ |\n| | `htmlOutput(outputId, inline, container, …)` |\n+----------------------------------------------------------------------------------------------------------------------------------+-------------------------------------------------------------------------------+\n\n: Table of render\\*() functions and their associated \\*Output() functions.\n\nThese are the core output types.\nSee [htmlwidgets.org](htmlwidgets.org) for many more options.\n\n## Inputs\n\nCollect values from the user.\n\nAccess the current value of an input object with `input$`.\nInput values are **reactive**.\n\n- `actionButton(inputId, label, icon, width, ...)`\n\n- `actionLink(inputId, label, icon, ...)`\n\n- `checkboxGroupInput(inputId, label, choices, selected, inline, width, choiceNames, choiceValues)`\n\n- `checkboxInput(inputId, label, value, width)`\n\n- `dateInput(inputId, label, value, min, max, format, startview, weekstart, language, width, autoclose, datesdisabled, daysofweekdisabled)`\n\n- `dateRangeInput(inputId, label, start, end, min, max, format, startview, weekstart, language, separator, width, autoclose)`\n\n- `fileInput(inputId, label, multiple, accept, width, buttonLabel, placeholder)`\n\n- `numericInput(inputId, label, value, min, max, step, width)`\n\n- `passwordInput(inputId, label, value, width, placeholder)`\n\n- `radioButtons(inputId, label, choices, selected, inline, width, choiceNames, choiceValues)`\n\n- `selectInput(inputId, label, choices, selected, multiple, selectize, width, size)`: Also `selectizeInput()`\n\n- `sliderInput(inputId, label, min, max, value, step, round, format, locale, ticks, animate, width, sep, pre, post, timeFormat, timezone, dragRange)`\n\n- `submitButton(text, icon, width)`: Prevent reactions for entire app\n\n- `textInput(inputId, label, value, width, placeholder)`: Also `textAreaInput()`\n\n\n\n## Reactivity\n\nReactive values work together with reactive functions.\nCall a reactive value from within the arguments of one of these functions to avoid the error.\n**Operation not allowed without an active reactive context.**\n\n![](images/reactivity-diagram.png){fig-align=\"center\"}\n\n::: {.callout-note appearance=\"minimal\" icon=\"false\" collapse=\"true\"}\n## Expand to read about the reactivity diagram {aria-hidden=\"true\"}\n\n### Phases in the reactivity diagram\n\n- Create your own reactive values\n - `reactiveValues()`\n - `reactiveFileReader()`\n - `reactivePoll()`\n - `*Input()`\n- Perform side effects\n - `observeEvent()`\n\n - `observe()`\n- Schedule updates\n - `invalidateLater()`\n- Create reactive expressions\n - `reactive()`\n- Remove reactivity\n - `isolate()`\n- React based on event\n - `eventReactive()`\n- Render reactive output\n - `render*()`\n:::\n\n### Create Your own Reactive Values\n\n- `*Input()` functions: (see front page) Each input function creates a reactive value stored as input\\$.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n # *Input() example\n ui <- fluidPage(\n textInput(\"a\",\"\",\"A\")\n )\n ```\n :::\n\n\n- `reactiveValues(...)`: Creates a list of reactive values whose values you can set.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n #reactiveValues example\n server <- function(input,output){\n rv <- reactiveValues() \n rv$number <- 5\n }\n ```\n :::\n\n\n### Create Reactive Expressions\n\n- `reactive(x, env, quoted, label, domain)`:\n\n - Reactive expressions:\n\n - cache their value to reduce computation\n\n - can be called elsewhere\n\n - notify dependencies when invalidated\n\n Call the expression with function sytrax, e.g. `re()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n library(shiny)\n \n ui <- fluidPage(\n textInput(\"a\",\"\",\"A\"), \n textInput(\"z\",\"\",\"Z\"), \n textOutput(\"b\"))\n \n server <- function(input,output){\n re <- reactive({ \n paste(input$a,input$z)})\n output$b <- renderText({\n re()\n }) \n }\n \n shinyApp(ui, server)\n ```\n :::\n\n\n### React Based on Event\n\n- `eventReactive(eventExpr, valueExpr, event.env, event.quoted, value.env, value.quoted, ..., label, domain, ignoreNULL, ignoreInit)`: Creates reactive expression with code in 2nd argument that only invalidates when reactive values in 1st argument change.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n library(shiny)\n \n ui <- fluidPage(\n textInput(\"a\",\"\",\"A\"), \n actionButton(\"go\",\"Go\"), \n textOutput(\"b\")\n )\n \n server <- function(input,output){\n re <- eventReactive(\n input$go,{input$a})\n output$b <- renderText({\n re()\n }) \n }\n ```\n :::\n\n\n### Render Reactive Output\n\n- `render*()` functions: (see front page) Builds an object to display.\n Will rerun code in body to rebuild the object whenever a reactive value in the code changes.\n Save the results to `output$`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n library(shiny)\n \n ui <- fluidPage(\n textInput(\"a\",\"\",\"A\"), \n textOutput(\"b\")\n )\n \n server <- function(input,output){\n output$b <-\n renderText({\n input$a\n })\n }\n \n shinyApp(ui, server)\n ```\n :::\n\n\n### Perform Side Effects\n\n- `observeEvent(eventExpr, handlerExpr, event.env, event.quoted, handler.env, handler.quoted, ..., label, suspended, priority, domain, autoDestroy, ignoreNULL, ignoreInit, once)`: Runs code in 2nd argument when reactive values in 1st argument change.\n See `observe()` for alternative.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n library(shiny)\n \n ui <- fluidPage(textInput(\"a\",\"\",\"A\"), actionButton(\"go\",\"Go\"))\n \n server <- function(input,output){\n observeEvent(input$go, {\n print(input$a)\n })\n }\n \n shinyApp(ui, server)\n ```\n :::\n\n\n### Remove Reactivity\n\n- `isolate(expr)`: Runs a code block.\n Returns a **non-reactive** copy of the results.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n library(shiny)\n \n ui <- fluidPage(\n textInput(\"a\",\"\",\"A\"), \n textOutput(\"b\")\n )\n \n server <- function(input,output){ \n output$b <- \n renderText({\n isolate({input$a})\n })\n }\n \n shinyApp(ui, server)\n ```\n :::\n\n\n## UI\n\nAn app's UI is an HTML document.\n\nUse Shiny's functions to assemble this HTML with R.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nfluidPage(\n textInput(\"a\",\"\")\n)\n```\n:::\n\n\nReturns HTML:\n\n``` html\n
\n
\n \n \n
\n
\n```\n\nAdd static HTML elements with **tags**, a list of functions that parallel common HTML tags, e.g. `tags$a()`.\nUnnamed arguments will be passed into the tag; named arguments will become tag attributes.\n\nRun `names(tags)` for a complete list.\n`tags$h1(\"Header\")` -\\> `

Header

`\n\nThe most common tags have wrapper functions.\nYou do not need to prefix their names with `tags$`.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nui <- fluidPage(\n h1(\"Header 1\"), #

Header 1

\n hr(), #
\n br(), #
\n p(strong(\"bold\")), #

bold

\n p(em(\"italic\")), #

italic

\n p(code(\"code\")), #

code

\n a(href=\"\", \"link\"), # link\n HTML(\"

Raw html

\") # display raw html\n)\n```\n:::\n\n\nTo include a CSS file, use `includeCSS()`, or\n\n1. Place the file in the `www` subdirectory\n\n2. Link to it with:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n tags$head(tags$link(rel = \"stylesheet\", \n type = \"text/css\", \n href = \"\"))\n ```\n :::\n\n\nTo include JavaScript, use `includeScript()`, or\n\n1. Place the file in the `www` subdirectory\n\n2. Link to it with:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n tags$head(tags$script(src = \"\"))\n ```\n :::\n\n\nTo include an image:\n\n1. Place the file in the `www` subdirectory\n\n2. Link to it with:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n img(src = \"\")\n ```\n :::\n\n\n## Layouts\n\nCombine multiple elements into a \"single element\" that has its own properties with a panel function, e.g.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nwellPanel(\n dateInput(\"a\", \"\"),\n submitButton()\n)\n```\n:::\n\n\nOther elements:\n\n- `absolutePanel()`\n- `conditionalPanel()`\n- `fixedPanel()`\n- `headerPanel()`\n- `inputPanel()`\n- `mainPanel()`\n- `navlistPanel()`\n- `sidebarPanel()`\n- `tabPanel()`\n- `tabsetPanel()`\n- `titlePanel()`\n- `wellPanel()`\n\nOrganize panels and elements into a layout with a layour function.\nAdd elements as arguments of the layout functions.\n\n- `sidebarLayout()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n ui <- fluidPage(\n sidebarLayout(\n sidebarPanel(),\n mainPanel()\n )\n )\n ```\n :::\n\n\n- `fluidRow()`\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n ui <- fluidPage(\n fluidRow(column(width = 4),\n column(width = 2, offset = 3)),\n fluidRow(column(width = 12))\n )\n ```\n :::\n\n\nAlso `flowLayout()`, `splitLayout()`, `verticalLayout()`, `fixedPage()`, and `fixedRow()`.\n\nLayer tabPanels on top of each other, and navigate between them with:\n\n\n::: {.cell}\n\n```{.r .cell-code}\nui <- fluidPage(\n tabsetPanel(\n tabPanel(\"tab1\", \"contents\"),\n tabPanel(\"tab2\", \"contents\"),\n tabPanel(\"tab3\", \"contents\")\n )\n)\n```\n:::\n\n::: {.cell}\n\n```{.r .cell-code}\nui <- fluidPage(\n navlistPanel(\n tabPanel(\"tab1\", \"contents\"),\n tabPanel(\"tab2\", \"contents\"),\n tabPanel(\"tab3\", \"contents\")\n )\n)\n```\n:::\n\n::: {.cell}\n\n```{.r .cell-code}\nui <- navbarPage(\n title = \"Page\",\n tabPanel(\"tab1\", \"contents\"),\n tabPanel(\"tab2\", \"contents\"),\n tabPanel(\"tab3\", \"contents\")\n)\n```\n:::\n\n\n## Themes\n\nUse the **bslib** pacage to add existing themes to your Shiny app ui, or make your own.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(bslib)\nui <- fluidPage(\n theme = bs_theme(\n boothswatch = \"darkly\",\n ...\n )\n)\n```\n:::\n\n\n- `bootswatch_themes()`: Get a list of themes.\n\nBuild your own theme by customizing individual arguments.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nbs_theme(bg = \"#558AC5\",\n fg = \"#F9B02D\",\n ...)\n```\n:::\n\n\n- `?bs_theme` for a full list of arguments.\n\n- `bs_themer()`: Place within the server function ot use the interactive theming widget.\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [shiny.rstudio.com](https://shiny.rstudio.com/)\n\nUpdated: 2023-06.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"shiny\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.7.4'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", "supporting": [], "filters": [ "rmarkdown/pagebreak.lua" diff --git a/_freeze/html/strings/execute-results/html.json b/_freeze/html/strings/execute-results/html.json index 39eeb3ae..799b82a9 100644 --- a/_freeze/html/strings/execute-results/html.json +++ b/_freeze/html/strings/execute-results/html.json @@ -1,8 +1,10 @@ { - "hash": "184b9c7031c5563ac73858db573e1597", + "hash": "d1db6b9c5164f0d6a34ab4b674767060", "result": { - "markdown": "---\ntitle: \"String manipulation with stringr :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: false\n---\n\n::: {.cell .column-margin}\n\"\"\n

\n

Download PDF

\n\n
\n

Translations (PDF)

\n* Spanish\n* Vietnamese\n:::\n\n\n\n\nThe **stringr** package provides a set of internally consistent tools for working with character strings, i.e. sequences of characters surrounded by quotation marks.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(stringr)\n```\n:::\n\n\n\n\n## Detect Matches\n\n- `str_detect(string, pattern, negate = FALSE)`: Detect the presence of a pattern match in a string.\n Also `str_like()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str(fruit, \"a\")\n ```\n :::\n\n\n- `str_starts(string, pattern, negate = FALSE)`: Detect the presence of a pattern match at the beginning of a string.\n Also `str_ends()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_starts(fruit, \"a\")\n ```\n :::\n\n\n- `str_which(string, pattern, negate = FALSE)`: Find the indexes of strings that contain a pattern match.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_which(fruit, \"a\")\n ```\n :::\n\n\n- `str_locate(string, pattern)`: Locate the positions of pattern matches in a string.\n Also `str_locate_all()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_locate(fruit, \"a\")\n ```\n :::\n\n\n- `str_count(string, pattern)`: Count the number of matches in a string.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_count(fruit, \"a\")\n ```\n :::\n\n\n## Mutate Strings\n\n- `str_sub() <- value`: Replace substrings by identifying the substrings with `str_sub()` and assigning into the results.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_sub(fruit, 1, 3) <- \"str\"\n ```\n :::\n\n\n- `str_replace(string, pattern, replacement)`: Replace the first matched pattern in each string.\n Also `str_remove()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_replace(fruit, \"p\", \"-\")\n ```\n :::\n\n\n- `str_replace_all(string, pattern, replacement)`: Replace all matched patterns in each string.\n Also `str_remove_all()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_replace_all(fruit, \"p\", \"-\")\n ```\n :::\n\n\n- `str_to_lower(string, locale = \"en\")`^1^: Convert strings to lower case.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_to_lower(sentences)\n ```\n :::\n\n\n- `str_to_upper(string, locale = \"en\")`^1^: Convert strings to upper case.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_to_upper(sentences)\n ```\n :::\n\n\n- `str_to_title(string, locale = \"en\")`^1^: Convert strings to title case.\n Also `str_to_setence()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_to_title(sentences)\n ```\n :::\n\n\n## Subset Strings\n\n- `str_sub(string, start = 1L, end = -1L)`: Extract substrings from a character vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_sub(fruit, 1, 3)\n str_sub(fruit, -2)\n ```\n :::\n\n\n- `str_subset(string, pattern, negate = FALSE)`: Return only the strings that contain a pattern match.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_subset(fruit, \"p\")\n ```\n :::\n\n\n- `str_extract(string, pattern)`: Return the first pattern match found in each string, as a vector.\n Also `str_extract_all()` to return every pattern match.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_extract(fruit, \"[aeiou]\")\n ```\n :::\n\n\n- `str_match(string, pattern)`: Return the first pattern match found in each string, as a matrix with a column for each ( ) group in pattern.\n Also `str_match_all()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_match(sentences, \"(a|the) ([^ +])\")\n ```\n :::\n\n\n## Join and Split\n\n- `str_c(..., sep = \"\", collapse = NULL)`: Join multiple strings into a single string.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_c(letters, LETTERS)\n ```\n :::\n\n\n- `str_flatten(string, collapse = \"\")`: Combines into a single string, separated by collapse.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_flatten(fruit, \", \")\n ```\n :::\n\n\n- `str_dup(string, times)`: Repeat strings times times.\n Also `str_unique()` to remove duplicates.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_dup(fruit, times = 2)\n ```\n :::\n\n\n- `str_split_fixed(string, pattern, n)`: Split a vector of strings into a matrix of substrings (splitting at occurrences of a pattern match).\n Also `str_split()` to return a list of substrings and `str_split_n()` to return the nth substring.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_split_fixed(sentences, \" \", n = 3)\n ```\n :::\n\n\n- `str_glue(..., .sep = \"\", .envir = parent.frame())`: Create a string from strings and {expressions} to evaluate.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_glue(\"Pi is {pi}\")\n ```\n :::\n\n\n- `str_glue_data(.x, ..., .sep = \"\", .envir = parent.frame(), .na = \"NA\")`: Use a data frame, list, or environment to create a string from strings and {expressions} to evaluate.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_glue_data(mtcars, \"{rownames(mtcars)} has {hp} hp\")\n ```\n :::\n\n\n## Manage Lengths\n\n- `str_length(string)`: The width of strings (i.e. number of code points, which generally equals the number of characters).\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_length(fruit)\n ```\n :::\n\n\n- `str_pad(string, width, side = c(\"left\", \"right\", \"both\"), pad = \" \")`: Pad strings to constant width.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_pad(fruit, 17)\n ```\n :::\n\n\n- `str_trunc(string, width, side = c(\"left\", \"right\", \"both\"), ellipsis = \"...\")`: Truncate the width of strings, replacing content with ellipsis.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_trunc(sentences, 6)\n ```\n :::\n\n\n- `str_trim(string, side = c(\"left\", \"right\", \"both\"))`: Trim whitespace from the start and/or end of a string.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_trim(str_pad(fruit, 17))\n ```\n :::\n\n\n- `str_squish(string)`: Trim white space from each end and collapse multiple spaces into single spaces.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_squish(str_pad(fruit, 17, \"both\"))\n ```\n :::\n\n\n## Order Strings\n\n- `str_order(x, decreasing = FALSE, na_last = TRUE, locale = \"en\", numeric = FALSE, ...)^1^`: Return the vector of indexes that sorts a character vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fruit[str_order(fruit)]\n ```\n :::\n\n\n- `str_sort(x, decreasing = FALSE, na_last = TRUE, locale = \"en\", numeric = FALSE, ...)^1^`: Sort a character vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_sort(fruit)\n ```\n :::\n\n\n## Helpers\n\n- `str_conv(string, encoding)`: Override the encoding of a string.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_conv(fruit, \"ISO-8859-1\")\n ```\n :::\n\n\n- `str_view_all(string, pattern, match = NA)`: View HTML rendering of all regex matches.\n Also `str_view()` to see only the first match.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_view_all(sentences, \"[aeiou]\")\n ```\n :::\n\n\n- `str_equal(x, y, locale = \"en\", ignore_case = FALSE, ...)`^1^: Determine if two strings are equivalent.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_equal(c(\"a\", \"b\"), c(\"a\", \"c\"))\n ```\n :::\n\n\n- `str_wrap(string, width = 80, indent = 0, exdent = 0)`: Wrap strings into nicely formatted paragraphs.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_wrap(sentences, 20)\n ```\n :::\n\n\n^1^ See for a complete list of locales.\n\n\n\n## Regular Expressions\n\nRegular expressions, or *regexps*, are a concise language for describing patterns in strings.\n\n### Need to Know\n\nPattern arguments in stringr are interpreted as regular expressions *after any special characters have been parsed*.\n\nIn R, you write regular expressions as *strings*, sequences of characters surrounded by quotes(`\"\"`) or single quotes (`''`).\n\nSome characters cannot be directly represented in an R string.\nThese must be represented as **special characters**, sequences of characters that have a specific meaning, e.g. `\\\\` represents `\\`, `\\\"` represents `\"`, and `\\n` represents a new line.\nRun `?\"'\"` to see a complete list.\n\nBecause of this, whenever a `\\` appears in a regular expression, you must write it as `\\\\` in the string that represents the regular expression.\n\nUse `writeLines()` to see how R views your string after all special characters have been parsed.\n\nFor example, `writeLines(\"\\\\.\")` will be parsed as `\\.`\n\nand `writeLines(\"\\\\ is a backslash\")` will be parsed as `\\ is a backslash`.\n\n### Interpretation\n\nPatterns in stringr are interpreted as regexs.\nTo change this default, wrap the pattern in one of:\n\n- `regex(pattern, ignore_case = FALSE, multiline = FALSE, comments = FALSE, dotall = FALSE, ...)`: Modifies a regex to ignore cases, match end of lines as well as end of strings, allow R comments within regexs, and/or to have `.` match everthing including `\\n`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_detect(\"I\", regex(\"i\", TRUE))\n ```\n :::\n\n\n- `fixed()`: Matches raw bytes but will miss some characters that can be represented in multiple ways (fast).\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_detect(\"\\u0130\", fixed(\"i\"))\n ```\n :::\n\n\n- `coll()`: Matches raw bytes and will use locale specific collation rules to recognize characters that can be represented in multiple ways (slow).\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_detect(\"\\u0130\", coll(\"i\", TRUE, locale = \"tr\"))\n ```\n :::\n\n\n- `boundary()`: Matches boundaries between characters, line_breaks, sentences, or words.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_split(sentences, boundary(\"word\"))\n ```\n :::\n\n\n### Match Characters\n\n\n::: {.cell}\n\n```{.r .cell-code}\nsee <- function(rx) str_view_all(\"abc ABC 123\\t.!?\\\\(){}\\n\", rx)\n```\n:::\n\n\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| string\\ | regex\\ | matches\\ | example | example output (highlighted characters are in \\<\\>) |\n| (type this) | (to mean this) | (which matches this) | | |\n+=============+================+===================================+======================+===================================================================+\n| | `a (etc.)` | `a (etc.)` | `see(\"a\")` | ``` |\n| | | | | bc ABC 123\\t.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\.` | `\\.` | `.` | ``` see(\"\\\\.\")`` ``` | ``` |\n| | | | | abc ABC 123\\t<.>!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\!` | `\\!` | `!` | `see(\"\\\\!\")` | ``` |\n| | | | | abc ABC 123\\t.?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\?` | `\\?` | `?` | `see(\"\\\\?\")` | ``` |\n| | | | | abc ABC 123\\t.!\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\\\\\` | `\\\\` | `\\` | `see(\"\\\\\\\\\")` | ``` |\n| | | | | abc ABC 123\\t.!?<\\>(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\(` | `\\(` | `(` | `see(\"\\\\(\")` | ``` |\n| | | | | abc ABC 123\\t.!?\\<(>){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\)` | `\\)` | `)` | `see(\"\\\\)\")` | ``` |\n| | | | | abc ABC 123\\t.!?\\(<)>{}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\{` | `\\{` | `{` | `see(\"\\\\{\")` | ``` |\n| | | | | abc ABC 123\\t.!?\\()<{>}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\}` | `\\}` | `}` | `see(\"\\\\}\")` | ``` |\n| | | | | abc ABC 123\\t.!?\\(){<}>\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\n` | `\\n` | new line (return) | `see(\"\\\\n\")` | ``` |\n| | | | | abc ABC 123\\t.!?\\(){}<\\n> |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\t` | `\\t` | tab | `see(\"\\\\t\")` | ``` |\n| | | | | abc ABC 123<\\t>.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\s` | `\\s` | any whitespace\\ | `see(\"\\\\s\")` | ``` |\n| | | (`\\S` for non-whitespaces) | | abc< >ABC< >123<\\t>.!?\\(){}<\\n> |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\d` | `\\d` | any digit\\ | `see(\"\\\\d\")` | ``` |\n| | | (`\\D` for non-digits) | | abc ABC <1><2><3>\\t.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\w` | `\\w` | any word character\\ | `see(\"\\\\w\")` | ``` |\n| | | (`\\W` for non-word characters) | | <1><2><3>\\t.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\b` | `\\b` | word boundaries | `see(\"\\\\b\")` | ``` |\n| | | | | <>abc<> <>ABC<> <>123<>\\t.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| | `[:digit:]`^1^ | digits | `see(\"[:digit:]\")` | ``` |\n| | | | | abc ABC <1><2><3>\\t.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| | `[:alpha:]`^1^ | letters | `see(\"[:alpha:]\")` | ``` |\n| | | | | 123\\t.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| | `[:lower:]`^1^ | lowercase letters | `see(\"[:lower:]\")` | ``` |\n| | | | | ABC 123\\t.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| | `[:upper:]`^1^ | uppercase letters | `see(\"[:upper:]\")` | ``` |\n| | | | | abc 123\\t.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| | `[:alnum:]`^1^ | letters and numbers | `see(\"[:alnum:]\")` | ``` |\n| | | | | <1><2><3>\\t.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| | `[:punct:]`^1^ | punctuation | `see(\"[:punct:]\")` | ``` |\n| | | | | abc ABC 123\\t<.><\\><(><)><{><}>\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| | `[:graph:]`^1^ | letters, numbers, and punctuation | `see(\"[:graph:]\")` | ``` |\n| | | | | <1><2><3>\\t<.><\\><(><)><{><}>\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| | `[:space:]`^1^ | space characters (i.e. `\\s`) | `see(\"[:space:]\")` | ``` |\n| | | | | abc< >ABC< >123<\\t>.!?\\(){}<\\n> |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| | `[:blank:]`^1^ | space and tab (but not new line) | `see(\"[:blank:]\")` | ``` |\n| | | | | abc< >ABC< >123<\\t>.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| | `.` | every character except a new line | `see(\".\")` | ``` |\n| | | | | < >< ><1><2><3><\\t><.><\\><(><)><{><}><\\n> |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n\n: 1Many base R functions require classes to be wrapped in a second set of \\[ \\], e.g. **\\[\\[:digit:\\]\\]**\n\n#### Classes\n\n- The `[:space:]` class includes new line, and the `[:blank:]` class\n - The `[:blank:]` class includes space and tab (`\\t`)\n- The `[:graph:]` class contains all non-space characters, including `[:punct:]`, `[:symbol:]`, `[:alnum:]`, `[:digit:]`, `[:alpha:]`, `[:lower:]`, and `[:upper:]`\n - `[:punct:]` contains punctuation: `. , : ; ? ! / * @ # - _ \" [ ] { } ( )`\n\n - `[:symbol:]` contains symbols: `` | ` = + ^ ~ < > $ ``\n\n - `[:alnum:]` contains alphanumeric characters, including `[:digit:]`, `[:alpha:]`, `[:lower:]`, and `[:upper:]`\n\n - `[:digit:]` contains the digits 0 through 9\n\n - `[:alpha:]` contains letters, including `[:upper:]` and `[:lower:]`\n\n - `[:upper:]` contains uppercase letters and `[:lower:]` contains lowercase letters\n- The regex `.` contains all characters in the above classes, except new line.\n\n### Alternates\n\n`alt <- function(rx) str_view_all(\"abcde\", rx)`\n\n+------------+--------------+-----------------+--------------------------------------+\n| regexp | matches | example | example output\\ |\n| | | | (highlighted characters are in \\<\\>) |\n+============+==============+=================+======================================+\n| `ab|d` | or | `alt(\"ab|d\")` | ``` |\n| | | | ce |\n| | | | ``` |\n+------------+--------------+-----------------+--------------------------------------+\n| `[abe]` | one of | `alt(\"[abe]\"` | ``` |\n| | | | cd |\n| | | | ``` |\n+------------+--------------+-----------------+--------------------------------------+\n| `[^abe]` | anything but | `alt(\"[^abe]\")` | ``` |\n| | | | abe |\n| | | | ``` |\n+------------+--------------+-----------------+--------------------------------------+\n| `[a-c]` | range | `alt(\"[a-c]\")` | ``` |\n| | | | de |\n| | | | ``` |\n+------------+--------------+-----------------+--------------------------------------+\n\n: Alternates\n\n### Anchors\n\n`anchor <- function(rx) str_view_all(\"aaa\", rx)`\n\n+------------+-----------------+----------------+--------------------------------------+\n| regexp | matches | example | example output\\ |\n| | | | (highlighted characters are in \\<\\>) |\n+============+=================+================+======================================+\n| `^a` | start of string | `anchor(\"^a\")` | ``` |\n| | | | aa |\n| | | | ``` |\n+------------+-----------------+----------------+--------------------------------------+\n| `a$` | end of string | `anchor(\"a$\")` | ``` |\n| | | | aa |\n| | | | ``` |\n+------------+-----------------+----------------+--------------------------------------+\n\n: Anchors\n\n### Look Arounds\n\n`look <- function(rx) str_view_all(\"bacad\", rx)`\n\n+-------------+-----------------+-------------------+--------------------------------------+\n| regexp | matches | example | example output\\ |\n| | | | (highlighted characters are in \\<\\>) |\n+=============+=================+===================+======================================+\n| `a(?=c)` | followed by | `look(\"a(?=c)\")` | ``` |\n| | | | bcad |\n| | | | ``` |\n+-------------+-----------------+-------------------+--------------------------------------+\n| `a(?!c)` | not followed by | `look(\"a(?!c)\")` | ``` |\n| | | | bacd |\n| | | | ``` |\n+-------------+-----------------+-------------------+--------------------------------------+\n| `(?<=b)a` | preceded by | `look(\"(?<=b)a\")` | ``` |\n| | | | bcad |\n| | | | ``` |\n+-------------+-----------------+-------------------+--------------------------------------+\n| `(?d |\n| | | | ``` |\n+-------------+-----------------+-------------------+--------------------------------------+\n\n: Look arounds\n\n### Quantifiers\n\n`quant <- function(rx) str_view_all(\".a.aa.aaa\", rx)`\n\n+-------------+---------------------+-------------------+--------------------------------------+\n| regexp | matches | example | example output\\ |\n| | | | (highlighted characters are in \\<\\>) |\n+=============+=====================+===================+======================================+\n| `a?` | zero or one | `quant(\"a?\")` | ``` |\n| | | | <>.<>.<>.<> |\n| | | | ``` |\n+-------------+---------------------+-------------------+--------------------------------------+\n| `a*` | zero or more | `quant(\"a*\")` | ``` |\n| | | | <>.<>.<>.<> |\n| | | | ``` |\n+-------------+---------------------+-------------------+--------------------------------------+\n| `a+` | one or more | `quant(\"a+\")` | ``` |\n| | | | ... |\n| | | | ``` |\n+-------------+---------------------+-------------------+--------------------------------------+\n| `a{n}` | exactly `n` | `quant(\"a{2}\")` | ``` |\n| | | | .a..a |\n| | | | ``` |\n+-------------+---------------------+-------------------+--------------------------------------+\n| `a{n, }` | `n` or more | `quant(\"a{2,}\")` | ``` |\n| | | | .a.. |\n| | | | ``` |\n+-------------+---------------------+-------------------+--------------------------------------+\n| `a{n, m}` | between `n` and `m` | `quant(\"a{2,4}\")` | ``` |\n| | | | .a.. |\n| | | | ``` |\n+-------------+---------------------+-------------------+--------------------------------------+\n\n: Quantifiers\n\n### Groups\n\n`ref <- function(rx) str_view_all(\"abbaab\", rx)`\n\nUse parentheses to set precedent (order of evaluation) and create groups\n\n+-------------+-----------------+------------------+--------------------------------------+\n| regexp | matches | example | example output\\ |\n| | | | (highlighted characters are in \\<\\>) |\n+=============+=================+==================+======================================+\n| `(ab|d)e` | sets precedence | `alt(\"(ab|d)e\")` | ``` |\n| | | | abc |\n| | | | ``` |\n+-------------+-----------------+------------------+--------------------------------------+\n\n: Groups\n\nUse an escaped number to refer to and duplicate parentheses groups that occur earlier in a pattern.\nRefer to each group by its order of appearance\n\n+-------------+----------------+----------------------+-------------------------------------------+--------------------------------------+\n| string\\ | regexp\\ | matches\\ | example\\ | example output\\ |\n| (type this) | (to mean this) | (which matches this) | (the result is the same as `ref(\"abba\")`) | (highlighted characters are in \\<\\>) |\n+=============+================+======================+===========================================+======================================+\n| `\\\\1` | `\\1` (etc.) | first () group, etc. | `ref(\"(a)(b)\\\\2\\\\1\")` | ``` |\n| | | | | ab |\n| | | | | ``` |\n+-------------+----------------+----------------------+-------------------------------------------+--------------------------------------+\n\n: More groups\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [stringr.tidyverse.org](https://stringr.tidyverse.org).\n\nUpdated: 2023-05.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"stringr\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.5.0'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", - "supporting": [], + "markdown": "---\ntitle: \"String manipulation with stringr :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: false\n---\n\n::: {.cell .column-margin}\n\"Hex\n

\n

Download PDF

\n\"\"/\n
\n

Translations (PDF)

\n* Spanish\n* Vietnamese\n:::\n\n\n\n\nThe **stringr** package provides a set of internally consistent tools for working with character strings, i.e. sequences of characters surrounded by quotation marks.\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(stringr)\n```\n:::\n\n\n\n\n## Detect Matches\n\n- `str_detect(string, pattern, negate = FALSE)`: Detect the presence of a pattern match in a string.\n Also `str_like()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str(fruit, \"a\")\n ```\n :::\n\n\n- `str_starts(string, pattern, negate = FALSE)`: Detect the presence of a pattern match at the beginning of a string.\n Also `str_ends()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_starts(fruit, \"a\")\n ```\n :::\n\n\n- `str_which(string, pattern, negate = FALSE)`: Find the indexes of strings that contain a pattern match.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_which(fruit, \"a\")\n ```\n :::\n\n\n- `str_locate(string, pattern)`: Locate the positions of pattern matches in a string.\n Also `str_locate_all()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_locate(fruit, \"a\")\n ```\n :::\n\n\n- `str_count(string, pattern)`: Count the number of matches in a string.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_count(fruit, \"a\")\n ```\n :::\n\n\n## Mutate Strings\n\n- `str_sub() <- value`: Replace substrings by identifying the substrings with `str_sub()` and assigning into the results.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_sub(fruit, 1, 3) <- \"str\"\n ```\n :::\n\n\n- `str_replace(string, pattern, replacement)`: Replace the first matched pattern in each string.\n Also `str_remove()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_replace(fruit, \"p\", \"-\")\n ```\n :::\n\n\n- `str_replace_all(string, pattern, replacement)`: Replace all matched patterns in each string.\n Also `str_remove_all()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_replace_all(fruit, \"p\", \"-\")\n ```\n :::\n\n\n- `str_to_lower(string, locale = \"en\")`^1^: Convert strings to lower case.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_to_lower(sentences)\n ```\n :::\n\n\n- `str_to_upper(string, locale = \"en\")`^1^: Convert strings to upper case.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_to_upper(sentences)\n ```\n :::\n\n\n- `str_to_title(string, locale = \"en\")`^1^: Convert strings to title case.\n Also `str_to_setence()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_to_title(sentences)\n ```\n :::\n\n\n## Subset Strings\n\n- `str_sub(string, start = 1L, end = -1L)`: Extract substrings from a character vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_sub(fruit, 1, 3)\n str_sub(fruit, -2)\n ```\n :::\n\n\n- `str_subset(string, pattern, negate = FALSE)`: Return only the strings that contain a pattern match.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_subset(fruit, \"p\")\n ```\n :::\n\n\n- `str_extract(string, pattern)`: Return the first pattern match found in each string, as a vector.\n Also `str_extract_all()` to return every pattern match.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_extract(fruit, \"[aeiou]\")\n ```\n :::\n\n\n- `str_match(string, pattern)`: Return the first pattern match found in each string, as a matrix with a column for each ( ) group in pattern.\n Also `str_match_all()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_match(sentences, \"(a|the) ([^ +])\")\n ```\n :::\n\n\n## Join and Split\n\n- `str_c(..., sep = \"\", collapse = NULL)`: Join multiple strings into a single string.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_c(letters, LETTERS)\n ```\n :::\n\n\n- `str_flatten(string, collapse = \"\")`: Combines into a single string, separated by collapse.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_flatten(fruit, \", \")\n ```\n :::\n\n\n- `str_dup(string, times)`: Repeat strings times times.\n Also `str_unique()` to remove duplicates.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_dup(fruit, times = 2)\n ```\n :::\n\n\n- `str_split_fixed(string, pattern, n)`: Split a vector of strings into a matrix of substrings (splitting at occurrences of a pattern match).\n Also `str_split()` to return a list of substrings and `str_split_n()` to return the nth substring.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_split_fixed(sentences, \" \", n = 3)\n ```\n :::\n\n\n- `str_glue(..., .sep = \"\", .envir = parent.frame())`: Create a string from strings and {expressions} to evaluate.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_glue(\"Pi is {pi}\")\n ```\n :::\n\n\n- `str_glue_data(.x, ..., .sep = \"\", .envir = parent.frame(), .na = \"NA\")`: Use a data frame, list, or environment to create a string from strings and {expressions} to evaluate.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_glue_data(mtcars, \"{rownames(mtcars)} has {hp} hp\")\n ```\n :::\n\n\n## Manage Lengths\n\n- `str_length(string)`: The width of strings (i.e. number of code points, which generally equals the number of characters).\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_length(fruit)\n ```\n :::\n\n\n- `str_pad(string, width, side = c(\"left\", \"right\", \"both\"), pad = \" \")`: Pad strings to constant width.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_pad(fruit, 17)\n ```\n :::\n\n\n- `str_trunc(string, width, side = c(\"left\", \"right\", \"both\"), ellipsis = \"...\")`: Truncate the width of strings, replacing content with ellipsis.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_trunc(sentences, 6)\n ```\n :::\n\n\n- `str_trim(string, side = c(\"left\", \"right\", \"both\"))`: Trim whitespace from the start and/or end of a string.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_trim(str_pad(fruit, 17))\n ```\n :::\n\n\n- `str_squish(string)`: Trim white space from each end and collapse multiple spaces into single spaces.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_squish(str_pad(fruit, 17, \"both\"))\n ```\n :::\n\n\n## Order Strings\n\n- `str_order(x, decreasing = FALSE, na_last = TRUE, locale = \"en\", numeric = FALSE, ...)^1^`: Return the vector of indexes that sorts a character vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fruit[str_order(fruit)]\n ```\n :::\n\n\n- `str_sort(x, decreasing = FALSE, na_last = TRUE, locale = \"en\", numeric = FALSE, ...)^1^`: Sort a character vector.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_sort(fruit)\n ```\n :::\n\n\n## Helpers\n\n- `str_conv(string, encoding)`: Override the encoding of a string.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_conv(fruit, \"ISO-8859-1\")\n ```\n :::\n\n\n- `str_view_all(string, pattern, match = NA)`: View HTML rendering of all regex matches.\n Also `str_view()` to see only the first match.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_view_all(sentences, \"[aeiou]\")\n ```\n :::\n\n\n- `str_equal(x, y, locale = \"en\", ignore_case = FALSE, ...)`^1^: Determine if two strings are equivalent.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_equal(c(\"a\", \"b\"), c(\"a\", \"c\"))\n ```\n :::\n\n\n- `str_wrap(string, width = 80, indent = 0, exdent = 0)`: Wrap strings into nicely formatted paragraphs.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_wrap(sentences, 20)\n ```\n :::\n\n\n^1^ See for a complete list of locales.\n\n\n\n## Regular Expressions\n\nRegular expressions, or *regexps*, are a concise language for describing patterns in strings.\n\n### Need to Know\n\nPattern arguments in stringr are interpreted as regular expressions *after any special characters have been parsed*.\n\nIn R, you write regular expressions as *strings*, sequences of characters surrounded by quotes(`\"\"`) or single quotes (`''`).\n\nSome characters cannot be directly represented in an R string.\nThese must be represented as **special characters**, sequences of characters that have a specific meaning, e.g. `\\\\` represents `\\`, `\\\"` represents `\"`, and `\\n` represents a new line.\nRun `?\"'\"` to see a complete list.\n\nBecause of this, whenever a `\\` appears in a regular expression, you must write it as `\\\\` in the string that represents the regular expression.\n\nUse `writeLines()` to see how R views your string after all special characters have been parsed.\n\nFor example, `writeLines(\"\\\\.\")` will be parsed as `\\.`\n\nand `writeLines(\"\\\\ is a backslash\")` will be parsed as `\\ is a backslash`.\n\n### Interpretation\n\nPatterns in stringr are interpreted as regexs.\nTo change this default, wrap the pattern in one of:\n\n- `regex(pattern, ignore_case = FALSE, multiline = FALSE, comments = FALSE, dotall = FALSE, ...)`: Modifies a regex to ignore cases, match end of lines as well as end of strings, allow R comments within regexs, and/or to have `.` match everthing including `\\n`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_detect(\"I\", regex(\"i\", TRUE))\n ```\n :::\n\n\n- `fixed()`: Matches raw bytes but will miss some characters that can be represented in multiple ways (fast).\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_detect(\"\\u0130\", fixed(\"i\"))\n ```\n :::\n\n\n- `coll()`: Matches raw bytes and will use locale specific collation rules to recognize characters that can be represented in multiple ways (slow).\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_detect(\"\\u0130\", coll(\"i\", TRUE, locale = \"tr\"))\n ```\n :::\n\n\n- `boundary()`: Matches boundaries between characters, line_breaks, sentences, or words.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n str_split(sentences, boundary(\"word\"))\n ```\n :::\n\n\n### Match Characters\n\n\n::: {.cell}\n\n```{.r .cell-code}\nsee <- function(rx) str_view_all(\"abc ABC 123\\t.!?\\\\(){}\\n\", rx)\n```\n:::\n\n\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| string\\ | regex\\ | matches\\ | example | example output (highlighted characters are in \\<\\>) |\n| (type this) | (to mean this) | (which matches this) | | |\n+=============+================+===================================+======================+===================================================================+\n| | `a (etc.)` | `a (etc.)` | `see(\"a\")` | ``` |\n| | | | | bc ABC 123\\t.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\.` | `\\.` | `.` | ``` see(\"\\\\.\")`` ``` | ``` |\n| | | | | abc ABC 123\\t<.>!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\!` | `\\!` | `!` | `see(\"\\\\!\")` | ``` |\n| | | | | abc ABC 123\\t.?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\?` | `\\?` | `?` | `see(\"\\\\?\")` | ``` |\n| | | | | abc ABC 123\\t.!\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\\\\\` | `\\\\` | `\\` | `see(\"\\\\\\\\\")` | ``` |\n| | | | | abc ABC 123\\t.!?<\\>(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\(` | `\\(` | `(` | `see(\"\\\\(\")` | ``` |\n| | | | | abc ABC 123\\t.!?\\<(>){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\)` | `\\)` | `)` | `see(\"\\\\)\")` | ``` |\n| | | | | abc ABC 123\\t.!?\\(<)>{}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\{` | `\\{` | `{` | `see(\"\\\\{\")` | ``` |\n| | | | | abc ABC 123\\t.!?\\()<{>}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\}` | `\\}` | `}` | `see(\"\\\\}\")` | ``` |\n| | | | | abc ABC 123\\t.!?\\(){<}>\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\n` | `\\n` | new line (return) | `see(\"\\\\n\")` | ``` |\n| | | | | abc ABC 123\\t.!?\\(){}<\\n> |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\t` | `\\t` | tab | `see(\"\\\\t\")` | ``` |\n| | | | | abc ABC 123<\\t>.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\s` | `\\s` | any whitespace\\ | `see(\"\\\\s\")` | ``` |\n| | | (`\\S` for non-whitespaces) | | abc< >ABC< >123<\\t>.!?\\(){}<\\n> |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\d` | `\\d` | any digit\\ | `see(\"\\\\d\")` | ``` |\n| | | (`\\D` for non-digits) | | abc ABC <1><2><3>\\t.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\w` | `\\w` | any word character\\ | `see(\"\\\\w\")` | ``` |\n| | | (`\\W` for non-word characters) | | <1><2><3>\\t.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| `\\\\b` | `\\b` | word boundaries | `see(\"\\\\b\")` | ``` |\n| | | | | <>abc<> <>ABC<> <>123<>\\t.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| | `[:digit:]`^1^ | digits | `see(\"[:digit:]\")` | ``` |\n| | | | | abc ABC <1><2><3>\\t.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| | `[:alpha:]`^1^ | letters | `see(\"[:alpha:]\")` | ``` |\n| | | | | 123\\t.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| | `[:lower:]`^1^ | lowercase letters | `see(\"[:lower:]\")` | ``` |\n| | | | | ABC 123\\t.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| | `[:upper:]`^1^ | uppercase letters | `see(\"[:upper:]\")` | ``` |\n| | | | | abc 123\\t.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| | `[:alnum:]`^1^ | letters and numbers | `see(\"[:alnum:]\")` | ``` |\n| | | | | <1><2><3>\\t.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| | `[:punct:]`^1^ | punctuation | `see(\"[:punct:]\")` | ``` |\n| | | | | abc ABC 123\\t<.><\\><(><)><{><}>\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| | `[:graph:]`^1^ | letters, numbers, and punctuation | `see(\"[:graph:]\")` | ``` |\n| | | | | <1><2><3>\\t<.><\\><(><)><{><}>\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| | `[:space:]`^1^ | space characters (i.e. `\\s`) | `see(\"[:space:]\")` | ``` |\n| | | | | abc< >ABC< >123<\\t>.!?\\(){}<\\n> |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| | `[:blank:]`^1^ | space and tab (but not new line) | `see(\"[:blank:]\")` | ``` |\n| | | | | abc< >ABC< >123<\\t>.!?\\(){}\\n |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n| | `.` | every character except a new line | `see(\".\")` | ``` |\n| | | | | < >< ><1><2><3><\\t><.><\\><(><)><{><}><\\n> |\n| | | | | ``` |\n+-------------+----------------+-----------------------------------+----------------------+-------------------------------------------------------------------+\n\n: 1Many base R functions require classes to be wrapped in a second set of \\[ \\], e.g. **\\[\\[:digit:\\]\\]**\n\n#### Classes\n\n- The `[:space:]` class includes new line, and the `[:blank:]` class\n - The `[:blank:]` class includes space and tab (`\\t`)\n- The `[:graph:]` class contains all non-space characters, including `[:punct:]`, `[:symbol:]`, `[:alnum:]`, `[:digit:]`, `[:alpha:]`, `[:lower:]`, and `[:upper:]`\n - `[:punct:]` contains punctuation: `. , : ; ? ! / * @ # - _ \" [ ] { } ( )`\n\n - `[:symbol:]` contains symbols: `` | ` = + ^ ~ < > $ ``\n\n - `[:alnum:]` contains alphanumeric characters, including `[:digit:]`, `[:alpha:]`, `[:lower:]`, and `[:upper:]`\n\n - `[:digit:]` contains the digits 0 through 9\n\n - `[:alpha:]` contains letters, including `[:upper:]` and `[:lower:]`\n\n - `[:upper:]` contains uppercase letters and `[:lower:]` contains lowercase letters\n- The regex `.` contains all characters in the above classes, except new line.\n\n### Alternates\n\n`alt <- function(rx) str_view_all(\"abcde\", rx)`\n\n+------------+--------------+-----------------+--------------------------------------+\n| regexp | matches | example | example output\\ |\n| | | | (highlighted characters are in \\<\\>) |\n+============+==============+=================+======================================+\n| `ab|d` | or | `alt(\"ab|d\")` | ``` |\n| | | | ce |\n| | | | ``` |\n+------------+--------------+-----------------+--------------------------------------+\n| `[abe]` | one of | `alt(\"[abe]\"` | ``` |\n| | | | cd |\n| | | | ``` |\n+------------+--------------+-----------------+--------------------------------------+\n| `[^abe]` | anything but | `alt(\"[^abe]\")` | ``` |\n| | | | abe |\n| | | | ``` |\n+------------+--------------+-----------------+--------------------------------------+\n| `[a-c]` | range | `alt(\"[a-c]\")` | ``` |\n| | | | de |\n| | | | ``` |\n+------------+--------------+-----------------+--------------------------------------+\n\n: Alternates\n\n### Anchors\n\n`anchor <- function(rx) str_view_all(\"aaa\", rx)`\n\n+------------+-----------------+----------------+--------------------------------------+\n| regexp | matches | example | example output\\ |\n| | | | (highlighted characters are in \\<\\>) |\n+============+=================+================+======================================+\n| `^a` | start of string | `anchor(\"^a\")` | ``` |\n| | | | aa |\n| | | | ``` |\n+------------+-----------------+----------------+--------------------------------------+\n| `a$` | end of string | `anchor(\"a$\")` | ``` |\n| | | | aa |\n| | | | ``` |\n+------------+-----------------+----------------+--------------------------------------+\n\n: Anchors\n\n### Look Arounds\n\n`look <- function(rx) str_view_all(\"bacad\", rx)`\n\n+-------------+-----------------+-------------------+--------------------------------------+\n| regexp | matches | example | example output\\ |\n| | | | (highlighted characters are in \\<\\>) |\n+=============+=================+===================+======================================+\n| `a(?=c)` | followed by | `look(\"a(?=c)\")` | ``` |\n| | | | bcad |\n| | | | ``` |\n+-------------+-----------------+-------------------+--------------------------------------+\n| `a(?!c)` | not followed by | `look(\"a(?!c)\")` | ``` |\n| | | | bacd |\n| | | | ``` |\n+-------------+-----------------+-------------------+--------------------------------------+\n| `(?<=b)a` | preceded by | `look(\"(?<=b)a\")` | ``` |\n| | | | bcad |\n| | | | ``` |\n+-------------+-----------------+-------------------+--------------------------------------+\n| `(?d |\n| | | | ``` |\n+-------------+-----------------+-------------------+--------------------------------------+\n\n: Look arounds\n\n### Quantifiers\n\n`quant <- function(rx) str_view_all(\".a.aa.aaa\", rx)`\n\n+-------------+---------------------+-------------------+--------------------------------------+\n| regexp | matches | example | example output\\ |\n| | | | (highlighted characters are in \\<\\>) |\n+=============+=====================+===================+======================================+\n| `a?` | zero or one | `quant(\"a?\")` | ``` |\n| | | | <>.<>.<>.<> |\n| | | | ``` |\n+-------------+---------------------+-------------------+--------------------------------------+\n| `a*` | zero or more | `quant(\"a*\")` | ``` |\n| | | | <>.<>.<>.<> |\n| | | | ``` |\n+-------------+---------------------+-------------------+--------------------------------------+\n| `a+` | one or more | `quant(\"a+\")` | ``` |\n| | | | ... |\n| | | | ``` |\n+-------------+---------------------+-------------------+--------------------------------------+\n| `a{n}` | exactly `n` | `quant(\"a{2}\")` | ``` |\n| | | | .a..a |\n| | | | ``` |\n+-------------+---------------------+-------------------+--------------------------------------+\n| `a{n, }` | `n` or more | `quant(\"a{2,}\")` | ``` |\n| | | | .a.. |\n| | | | ``` |\n+-------------+---------------------+-------------------+--------------------------------------+\n| `a{n, m}` | between `n` and `m` | `quant(\"a{2,4}\")` | ``` |\n| | | | .a.. |\n| | | | ``` |\n+-------------+---------------------+-------------------+--------------------------------------+\n\n: Quantifiers\n\n### Groups\n\n`ref <- function(rx) str_view_all(\"abbaab\", rx)`\n\nUse parentheses to set precedent (order of evaluation) and create groups\n\n+-------------+-----------------+------------------+--------------------------------------+\n| regexp | matches | example | example output\\ |\n| | | | (highlighted characters are in \\<\\>) |\n+=============+=================+==================+======================================+\n| `(ab|d)e` | sets precedence | `alt(\"(ab|d)e\")` | ``` |\n| | | | abc |\n| | | | ``` |\n+-------------+-----------------+------------------+--------------------------------------+\n\n: Groups\n\nUse an escaped number to refer to and duplicate parentheses groups that occur earlier in a pattern.\nRefer to each group by its order of appearance\n\n+-------------+----------------+----------------------+-------------------------------------------+--------------------------------------+\n| string\\ | regexp\\ | matches\\ | example\\ | example output\\ |\n| (type this) | (to mean this) | (which matches this) | (the result is the same as `ref(\"abba\")`) | (highlighted characters are in \\<\\>) |\n+=============+================+======================+===========================================+======================================+\n| `\\\\1` | `\\1` (etc.) | first () group, etc. | `ref(\"(a)(b)\\\\2\\\\1\")` | ``` |\n| | | | | ab |\n| | | | | ``` |\n+-------------+----------------+----------------------+-------------------------------------------+--------------------------------------+\n\n: More groups\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [stringr.tidyverse.org](https://stringr.tidyverse.org).\n\nUpdated: 2023-06.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"stringr\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.5.0'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", + "supporting": [ + "strings_files" + ], "filters": [ "rmarkdown/pagebreak.lua" ], diff --git a/_freeze/html/tidyr/execute-results/html.json b/_freeze/html/tidyr/execute-results/html.json index aedcfe99..9e9d97a8 100644 --- a/_freeze/html/tidyr/execute-results/html.json +++ b/_freeze/html/tidyr/execute-results/html.json @@ -1,7 +1,7 @@ { - "hash": "2e18f643eed108fb7cbb49881b382b81", + "hash": "587427f3469d90d5a6d6e737b571856f", "result": { - "markdown": "---\ntitle: \"Data tidying with tidyr :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: false\n---\n\n::: {.cell .column-margin}\n\"\"\n

\n

Download PDF

\n\n
\n

Translations (PDF)

\n* Chinese\n:::\n\n\n\n\n**Tidy data** is a way to organize tabular data in a consistent data structure across packages.\nA table is tidy if:\n\n- Each **variable** is in its own **column**\n- Each **observation**, or **case**, is in its own **row**\n- Access **variables** as **vectors**\n- Preserve **cases** in vectorized operations\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(tidyr)\nlibrary(tibble)\n```\n:::\n\n\n\n\n## Tibbles\n\n### An Enhanced Data Frame\n\nTibbles are a table format provided by the **tibble** package.\nThey inherit the data frame class, but have improved behaviors:\n\n- **Subset** a new tibble with `]`, a vector with `[[` and `$`.\n\n- **No partial matching** when subsetting columns.\n\n- **Display** concise views of the data on one screen.\n\n- `options(tibble.print_max = n, tibble.print_min = m, tibble.width = Inf)`: Control default display settings.\n\n- `View()` or `glimpse()`: View the entire data set.\n\n### Construct a Tibble\n\n- `tibble(...)`: Construct by columns.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n tibble(\n x = 1:3, \n y = c(\"a\", \"b\", \"c\")\n )\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 3 × 2\n x y \n \n 1 1 a \n 2 2 b \n 3 3 c \n ```\n :::\n :::\n\n\n- `tribble(...)`: Construct by rows.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n tribble(\n ~x, ~y,\n 1, \"a\",\n 2, \"b\",\n 3, \"c\"\n )\n ```\n :::\n\n\n- `as_tibble(x, ...)`: Convert a data frame to a tibble.\n\n- `enframe(x, name = \"name\", value = \"value\")`: Convert a named vector to a tibble.\n Also `deframe()`.\n\n- `is_tibble(x)`: Test whether x is a tibble.\n\n## Reshape Data\n\nPivot data to reorganize values into a new layout.\n\n- `pivot_longer(data, cols, name_to = \"name\", values_to = \"value\", values_drop_na = FALSE)`: \"Lengthen\" data by collapsing several columns into two.\n\n - The initial `table4a` looks like the following:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n table4a\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 3 × 3\n country `1999` `2000`\n \n 1 Afghanistan 745 2666\n 2 Brazil 37737 80488\n 3 China 212258 213766\n ```\n :::\n :::\n\n\n - Column names move to a new `names_to` column and values to a new `values_to` column. The output of `pivot_longer()` will look like the following:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pivot_longer(table4a, cols = 2:3, names_to = \"year\", values_to = \"cases\")\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 6 × 3\n country year cases\n \n 1 Afghanistan 1999 745\n 2 Afghanistan 2000 2666\n 3 Brazil 1999 37737\n 4 Brazil 2000 80488\n 5 China 1999 212258\n 6 China 2000 213766\n ```\n :::\n :::\n\n\n- `pivot_wider(data, name_from = \"name\", values_from = \"value\")`: The inverse of `pivot_longer()`.\n \"Widen\" data by expanding two columns into several.\n\n - The initial `table2` looks like the following:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n table2\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 12 × 4\n country year type count\n \n 1 Afghanistan 1999 cases 745\n 2 Afghanistan 1999 population 19987071\n 3 Afghanistan 2000 cases 2666\n 4 Afghanistan 2000 population 20595360\n 5 Brazil 1999 cases 37737\n 6 Brazil 1999 population 172006362\n 7 Brazil 2000 cases 80488\n 8 Brazil 2000 population 174504898\n 9 China 1999 cases 212258\n 10 China 1999 population 1272915272\n 11 China 2000 cases 213766\n 12 China 2000 population 1280428583\n ```\n :::\n :::\n\n\n - One column provides the new column names, the other the values. The output of `pivot_wider()` will look like the following:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pivot_wider(table2, names_from = type, values_from = count)\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 6 × 4\n country year cases population\n \n 1 Afghanistan 1999 745 19987071\n 2 Afghanistan 2000 2666 20595360\n 3 Brazil 1999 37737 172006362\n 4 Brazil 2000 80488 174504898\n 5 China 1999 212258 1272915272\n 6 China 2000 213766 1280428583\n ```\n :::\n :::\n\n\n## Split Cells\n\nUse these functions to split or combine cells into individual, isolated values.\n\n- `unite(data, col, ..., sep = \"_\", remove = TRUE, na.rm = FALSE)`: Collapse cells across several columns into a single column.\n\n - The initial `table5` looks like the following:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n table5\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 6 × 4\n country century year rate \n \n 1 Afghanistan 19 99 745/19987071 \n 2 Afghanistan 20 00 2666/20595360 \n 3 Brazil 19 99 37737/172006362 \n 4 Brazil 20 00 80488/174504898 \n 5 China 19 99 212258/1272915272\n 6 China 20 00 213766/1280428583\n ```\n :::\n :::\n\n\n - The output of `unite()` will look like the following:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n unite(table5, century, year, col = \"year\", sep = \"\")\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 6 × 3\n country year rate \n \n 1 Afghanistan 1999 745/19987071 \n 2 Afghanistan 2000 2666/20595360 \n 3 Brazil 1999 37737/172006362 \n 4 Brazil 2000 80488/174504898 \n 5 China 1999 212258/1272915272\n 6 China 2000 213766/1280428583\n ```\n :::\n :::\n\n\n- `separate(data, col, into, sep = \"[^[:alnum:]]+\", remove = TRUE, convert = FALSE, extra = \"warn\", fill = \"warn\", ...)`: Separate each cell in a column into several columns.\n Also `extract()`.\n\n - The initial `table3` looks like the following:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n table3\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 6 × 3\n country year rate \n \n 1 Afghanistan 1999 745/19987071 \n 2 Afghanistan 2000 2666/20595360 \n 3 Brazil 1999 37737/172006362 \n 4 Brazil 2000 80488/174504898 \n 5 China 1999 212258/1272915272\n 6 China 2000 213766/1280428583\n ```\n :::\n :::\n\n\n - The output of `separate()` will look like the following:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n separate(table3, rate, sep = \"/\", into = c(\"cases\", \"pop\"))\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 6 × 4\n country year cases pop \n \n 1 Afghanistan 1999 745 19987071 \n 2 Afghanistan 2000 2666 20595360 \n 3 Brazil 1999 37737 172006362 \n 4 Brazil 2000 80488 174504898 \n 5 China 1999 212258 1272915272\n 6 China 2000 213766 1280428583\n ```\n :::\n :::\n\n\n- `separate_rows(data, ..., sep = \"[^[:alnum:].]+\", convert = FALSE)`: Separate each cell in a column into several rows.\n\n - The initial `table3` looks like the following:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n table3\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 6 × 3\n country year rate \n \n 1 Afghanistan 1999 745/19987071 \n 2 Afghanistan 2000 2666/20595360 \n 3 Brazil 1999 37737/172006362 \n 4 Brazil 2000 80488/174504898 \n 5 China 1999 212258/1272915272\n 6 China 2000 213766/1280428583\n ```\n :::\n :::\n\n\n - The output of `separate_rows()` will look like the following:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n separate_rows(table3, rate, sep = \"/\")\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 12 × 3\n country year rate \n \n 1 Afghanistan 1999 745 \n 2 Afghanistan 1999 19987071 \n 3 Afghanistan 2000 2666 \n 4 Afghanistan 2000 20595360 \n 5 Brazil 1999 37737 \n 6 Brazil 1999 172006362 \n 7 Brazil 2000 80488 \n 8 Brazil 2000 174504898 \n 9 China 1999 212258 \n 10 China 1999 1272915272\n 11 China 2000 213766 \n 12 China 2000 1280428583\n ```\n :::\n :::\n\n\n## Expand Tables\n\nCreate new combinations of variables or identify implicit missing values (combinations of variables not present in the data).\n\n- `expand(data, ...)`: Create a new tibble with all possible combinations of the values of the variables listed in ... Drop other variables.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n expand(mtcars, cyl, gear, carb)\n ```\n :::\n\n\n- `complete(data, ..., fill = list())`: Add missing possible combinations of values of variables listed in ... Fill remaining variables with NA.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n complete(mtcars, cyl, gear, carb)\n ```\n :::\n\n\n## Handle Missing Values\n\nDrop or replace explicit missing values (`NA`).\n\n\n::: {.cell}\n\n```{.r .cell-code}\nx <- tribble(\n ~x1, ~x2,\n \"A\", 1,\n \"B\", NA,\n \"C\", NA,\n \"D\", 3,\n \"E\", NA\n)\n```\n:::\n\n\n- `drop_na(data, ...)`: Drop rows containing `NA`s in ... columns.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n drop_na(x, x2)\n ```\n :::\n\n\n- `fill(data, ..., .direction = \"down\")`: Fill in `NA`s in ... columns using the next or previous value.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fill(x, x2)\n ```\n :::\n\n\n- `replace_na(data, replace)`: Specify a value to replace `NA` in selected columns.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n replace_na(x, list(x2 = 2))\n ```\n :::\n\n\n\n\n## Nested Data\n\nA **nested data frame** stores individual tables as a list-column of data frames within a larger organizing data frame.\nList-columns can also be lists of vectors or lists of varying data types.\nUse a nested data frame to:\n\n- Preserve relationships between observations and subsets of data. Preserve the type of the variables being nested (factors and datetimes aren't coerced to character).\n- Manipulate many sub-tables are once with **purrr** functions like `map()`, `map2()`, or `pmap()` or with **dplyr** `rowwise()` grouping.\n\n### Create Nested Data\n\n- `nest(data, ...)`: Moves groups of cells into a list-column of a data frame. Use alone or with `dplyr::group_by()`.\n\n1. Group the data frame with `group_by()` and use `nest()` to move the groups into a list-column.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n n_storms <- storms |>\n group_by(name) |>\n nest()\n ```\n :::\n\n\n2. Use `nest(new_col = c(x,y))` to specify the columns to group using `dplyr::select()` syntax.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n n_storms <- storms |>\n nest(data = c(year:long))\n ```\n :::\n\n\n- Index list-columns with `[[]]`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n n_storms$data[[1]]\n ```\n :::\n\n\n### Create Tibbles With List-Columns\n\n- `tibble::tribble(...)`: Makes list-columns when needed.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n tribble(\n ~max, ~seq,\n 3, 1:3,\n 4, 1:4,\n 5, 1:5\n )\n ```\n :::\n\n\n- `tibble::tibble(...)`: Saves list input as list-columns.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n tibble(\n max = c(3,4,5),\n seq = list(1:3, 1:4, 1:5)\n )\n ```\n :::\n\n\n- `tibble::enframe(x, name = \"name\", value = \"value\")`: Convert multi-level list to a tibble with list-cols.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n enframe(list(\"3\" = 1:3, \"4\" = 1:4, \"5\" = 1:5), \"max\", \"seq\")\n ```\n :::\n\n\n### Output List-Columns From Other Functions\n\n- `dplyr::mutate()`, `transmute()`, and `summarise()` will output list-columns if they return a list.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |>\n group_by(cyl) |>\n summarise(q = list(quantile(mpg)))\n ```\n :::\n\n\n### Reshape Nested Data\n\n- `unnest(data, cols, ..., keep_empty = FALSE)`: Flatten nested columns back to regular columns.\n The inverse of `nest()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n n_storms |> unnest(data)\n ```\n :::\n\n\n- `unnest_longer(data, col, values_to = NULL, indices_to = NULL)`: Turn each element of a list-column into a row.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n starwars |>\n select(name, films) |>\n unnest_longer(films)\n ```\n :::\n\n\n- `unnest_wider(data, col)`: Turn each element of a list-column into a regular column.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n starwars |>\n select(name, films) |>\n unnest_wider(films, names_sep = \"_\")\n ```\n :::\n\n\n- `hoist(.data, .col, ..., remove = TRUE)`: Selectively pull list components out into their own top-level columns.\n Uses `purrr::pluck()` syntax for selecting from lists.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n starwars |>\n select(name, films) |>\n hoist(films, first_film = 1, second_film = 2)\n ```\n :::\n\n\n### Transform Nested Data\n\nA vectorized function takes a vector, transforms each element in parallel, and returns a vector of the same length.\nBy themselves vectorized functions cannot work with lists, such as list-columns.\n\n- `dplyr::rowwise(.data, ...)`: Group data so that each row is one group, and within the groups, elements of list-columns appear directly (accessed with `[[`), not as lists of length one.\n **When you use rowwise(), dplyr functions will seem to apply functions to list-columns in a vectorized fashion.**\n\n- Apply a function to a list-column and **create a new list-column.** In this example, `dim()` returns two values per row and so is wrapped with `list()` to tell `mutate()` to create a list-column.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n n_storms |>\n rowwise() |>\n mutate(n = list(dim(data))) # dim() returns two values per row, wrap with list to tell mutate to create a list-column\n ```\n :::\n\n\n- Apply a function to a list-column and **create a regular column.** In this example, `nrow()` returns one integer per row.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n n_storms |>\n rowwise() |>\n mutate(n = nrow(data)) # nrow() returns one integer per row\n ```\n :::\n\n\n- Collapse **multiple list-columns** into a single list-column.\n In this example, `append()` returns a list for each row, so col type must be list.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n starwars |>\n rowwise() |>\n mutate(transport = list(append(vehicles, starships))) # append() returns a list for each row, so col type must be list\n ```\n :::\n\n\n- Apply a function to **multiple list-columns.** In this example, `length()` returns one integer per row.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n starwars |>\n rowwise() |>\n mutate(n_transports = length(c(vehicles, starships)))\n # length() returns one integer per row\n ```\n :::\n\n\n- See **purrr** package for more list functions.\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [tidyr.tidyverse.org](https://tidyr.tidyverse.org).\n\nUpdated: 2023-05.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"tidyr\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.3.0'\n```\n:::\n\n```{.r .cell-code}\npackageVersion(\"tibble\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '3.2.1'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", + "markdown": "---\ntitle: \"Data tidying with tidyr :: Cheatsheet\"\ndescription: \" \"\nimage-alt: \"\"\nexecute:\n eval: true\n output: false\n warning: false\n---\n\n::: {.cell .column-margin}\n\"Hex\n

\n

Download PDF

\n\"\"/\n
\n

Translations (PDF)

\n* Chinese\n:::\n\n\n\n\n**Tidy data** is a way to organize tabular data in a consistent data structure across packages.\nA table is tidy if:\n\n- Each **variable** is in its own **column**\n- Each **observation**, or **case**, is in its own **row**\n- Access **variables** as **vectors**\n- Preserve **cases** in vectorized operations\n\n\n::: {.cell}\n\n```{.r .cell-code}\nlibrary(tidyr)\nlibrary(tibble)\n```\n:::\n\n\n\n\n## Tibbles\n\n### An Enhanced Data Frame\n\nTibbles are a table format provided by the **tibble** package.\nThey inherit the data frame class, but have improved behaviors:\n\n- **Subset** a new tibble with `]`, a vector with `[[` and `$`.\n\n- **No partial matching** when subsetting columns.\n\n- **Display** concise views of the data on one screen.\n\n- `options(tibble.print_max = n, tibble.print_min = m, tibble.width = Inf)`: Control default display settings.\n\n- `View()` or `glimpse()`: View the entire data set.\n\n### Construct a Tibble\n\n- `tibble(...)`: Construct by columns.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n tibble(\n x = 1:3, \n y = c(\"a\", \"b\", \"c\")\n )\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 3 × 2\n x y \n \n 1 1 a \n 2 2 b \n 3 3 c \n ```\n :::\n :::\n\n\n- `tribble(...)`: Construct by rows.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n tribble(\n ~x, ~y,\n 1, \"a\",\n 2, \"b\",\n 3, \"c\"\n )\n ```\n :::\n\n\n- `as_tibble(x, ...)`: Convert a data frame to a tibble.\n\n- `enframe(x, name = \"name\", value = \"value\")`: Convert a named vector to a tibble.\n Also `deframe()`.\n\n- `is_tibble(x)`: Test whether x is a tibble.\n\n## Reshape Data\n\nPivot data to reorganize values into a new layout.\n\n- `pivot_longer(data, cols, name_to = \"name\", values_to = \"value\", values_drop_na = FALSE)`: \"Lengthen\" data by collapsing several columns into two.\n\n - The initial `table4a` looks like the following:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n table4a\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 3 × 3\n country `1999` `2000`\n \n 1 Afghanistan 745 2666\n 2 Brazil 37737 80488\n 3 China 212258 213766\n ```\n :::\n :::\n\n\n - Column names move to a new `names_to` column and values to a new `values_to` column. The output of `pivot_longer()` will look like the following:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pivot_longer(table4a, cols = 2:3, names_to = \"year\", values_to = \"cases\")\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 6 × 3\n country year cases\n \n 1 Afghanistan 1999 745\n 2 Afghanistan 2000 2666\n 3 Brazil 1999 37737\n 4 Brazil 2000 80488\n 5 China 1999 212258\n 6 China 2000 213766\n ```\n :::\n :::\n\n\n- `pivot_wider(data, name_from = \"name\", values_from = \"value\")`: The inverse of `pivot_longer()`.\n \"Widen\" data by expanding two columns into several.\n\n - The initial `table2` looks like the following:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n table2\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 12 × 4\n country year type count\n \n 1 Afghanistan 1999 cases 745\n 2 Afghanistan 1999 population 19987071\n 3 Afghanistan 2000 cases 2666\n 4 Afghanistan 2000 population 20595360\n 5 Brazil 1999 cases 37737\n 6 Brazil 1999 population 172006362\n 7 Brazil 2000 cases 80488\n 8 Brazil 2000 population 174504898\n 9 China 1999 cases 212258\n 10 China 1999 population 1272915272\n 11 China 2000 cases 213766\n 12 China 2000 population 1280428583\n ```\n :::\n :::\n\n\n - One column provides the new column names, the other the values. The output of `pivot_wider()` will look like the following:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n pivot_wider(table2, names_from = type, values_from = count)\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 6 × 4\n country year cases population\n \n 1 Afghanistan 1999 745 19987071\n 2 Afghanistan 2000 2666 20595360\n 3 Brazil 1999 37737 172006362\n 4 Brazil 2000 80488 174504898\n 5 China 1999 212258 1272915272\n 6 China 2000 213766 1280428583\n ```\n :::\n :::\n\n\n## Split Cells\n\nUse these functions to split or combine cells into individual, isolated values.\n\n- `unite(data, col, ..., sep = \"_\", remove = TRUE, na.rm = FALSE)`: Collapse cells across several columns into a single column.\n\n - The initial `table5` looks like the following:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n table5\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 6 × 4\n country century year rate \n \n 1 Afghanistan 19 99 745/19987071 \n 2 Afghanistan 20 00 2666/20595360 \n 3 Brazil 19 99 37737/172006362 \n 4 Brazil 20 00 80488/174504898 \n 5 China 19 99 212258/1272915272\n 6 China 20 00 213766/1280428583\n ```\n :::\n :::\n\n\n - The output of `unite()` will look like the following:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n unite(table5, century, year, col = \"year\", sep = \"\")\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 6 × 3\n country year rate \n \n 1 Afghanistan 1999 745/19987071 \n 2 Afghanistan 2000 2666/20595360 \n 3 Brazil 1999 37737/172006362 \n 4 Brazil 2000 80488/174504898 \n 5 China 1999 212258/1272915272\n 6 China 2000 213766/1280428583\n ```\n :::\n :::\n\n\n- `separate(data, col, into, sep = \"[^[:alnum:]]+\", remove = TRUE, convert = FALSE, extra = \"warn\", fill = \"warn\", ...)`: Separate each cell in a column into several columns.\n Also `extract()`.\n\n - The initial `table3` looks like the following:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n table3\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 6 × 3\n country year rate \n \n 1 Afghanistan 1999 745/19987071 \n 2 Afghanistan 2000 2666/20595360 \n 3 Brazil 1999 37737/172006362 \n 4 Brazil 2000 80488/174504898 \n 5 China 1999 212258/1272915272\n 6 China 2000 213766/1280428583\n ```\n :::\n :::\n\n\n - The output of `separate()` will look like the following:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n separate(table3, rate, sep = \"/\", into = c(\"cases\", \"pop\"))\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 6 × 4\n country year cases pop \n \n 1 Afghanistan 1999 745 19987071 \n 2 Afghanistan 2000 2666 20595360 \n 3 Brazil 1999 37737 172006362 \n 4 Brazil 2000 80488 174504898 \n 5 China 1999 212258 1272915272\n 6 China 2000 213766 1280428583\n ```\n :::\n :::\n\n\n- `separate_rows(data, ..., sep = \"[^[:alnum:].]+\", convert = FALSE)`: Separate each cell in a column into several rows.\n\n - The initial `table3` looks like the following:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n table3\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 6 × 3\n country year rate \n \n 1 Afghanistan 1999 745/19987071 \n 2 Afghanistan 2000 2666/20595360 \n 3 Brazil 1999 37737/172006362 \n 4 Brazil 2000 80488/174504898 \n 5 China 1999 212258/1272915272\n 6 China 2000 213766/1280428583\n ```\n :::\n :::\n\n\n - The output of `separate_rows()` will look like the following:\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n separate_rows(table3, rate, sep = \"/\")\n ```\n \n ::: {.cell-output .cell-output-stdout}\n ```\n # A tibble: 12 × 3\n country year rate \n \n 1 Afghanistan 1999 745 \n 2 Afghanistan 1999 19987071 \n 3 Afghanistan 2000 2666 \n 4 Afghanistan 2000 20595360 \n 5 Brazil 1999 37737 \n 6 Brazil 1999 172006362 \n 7 Brazil 2000 80488 \n 8 Brazil 2000 174504898 \n 9 China 1999 212258 \n 10 China 1999 1272915272\n 11 China 2000 213766 \n 12 China 2000 1280428583\n ```\n :::\n :::\n\n\n## Expand Tables\n\nCreate new combinations of variables or identify implicit missing values (combinations of variables not present in the data).\n\n- `expand(data, ...)`: Create a new tibble with all possible combinations of the values of the variables listed in ... Drop other variables.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n expand(mtcars, cyl, gear, carb)\n ```\n :::\n\n\n- `complete(data, ..., fill = list())`: Add missing possible combinations of values of variables listed in ... Fill remaining variables with NA.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n complete(mtcars, cyl, gear, carb)\n ```\n :::\n\n\n## Handle Missing Values\n\nDrop or replace explicit missing values (`NA`).\n\n\n::: {.cell}\n\n```{.r .cell-code}\nx <- tribble(\n ~x1, ~x2,\n \"A\", 1,\n \"B\", NA,\n \"C\", NA,\n \"D\", 3,\n \"E\", NA\n)\n```\n:::\n\n\n- `drop_na(data, ...)`: Drop rows containing `NA`s in ... columns.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n drop_na(x, x2)\n ```\n :::\n\n\n- `fill(data, ..., .direction = \"down\")`: Fill in `NA`s in ... columns using the next or previous value.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n fill(x, x2)\n ```\n :::\n\n\n- `replace_na(data, replace)`: Specify a value to replace `NA` in selected columns.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n replace_na(x, list(x2 = 2))\n ```\n :::\n\n\n\n\n## Nested Data\n\nA **nested data frame** stores individual tables as a list-column of data frames within a larger organizing data frame.\nList-columns can also be lists of vectors or lists of varying data types.\nUse a nested data frame to:\n\n- Preserve relationships between observations and subsets of data. Preserve the type of the variables being nested (factors and datetimes aren't coerced to character).\n- Manipulate many sub-tables are once with **purrr** functions like `map()`, `map2()`, or `pmap()` or with **dplyr** `rowwise()` grouping.\n\n### Create Nested Data\n\n- `nest(data, ...)`: Moves groups of cells into a list-column of a data frame. Use alone or with `dplyr::group_by()`.\n\n1. Group the data frame with `group_by()` and use `nest()` to move the groups into a list-column.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n n_storms <- storms |>\n group_by(name) |>\n nest()\n ```\n :::\n\n\n2. Use `nest(new_col = c(x,y))` to specify the columns to group using `dplyr::select()` syntax.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n n_storms <- storms |>\n nest(data = c(year:long))\n ```\n :::\n\n\n- Index list-columns with `[[]]`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n n_storms$data[[1]]\n ```\n :::\n\n\n### Create Tibbles With List-Columns\n\n- `tibble::tribble(...)`: Makes list-columns when needed.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n tribble(\n ~max, ~seq,\n 3, 1:3,\n 4, 1:4,\n 5, 1:5\n )\n ```\n :::\n\n\n- `tibble::tibble(...)`: Saves list input as list-columns.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n tibble(\n max = c(3,4,5),\n seq = list(1:3, 1:4, 1:5)\n )\n ```\n :::\n\n\n- `tibble::enframe(x, name = \"name\", value = \"value\")`: Convert multi-level list to a tibble with list-cols.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n enframe(list(\"3\" = 1:3, \"4\" = 1:4, \"5\" = 1:5), \"max\", \"seq\")\n ```\n :::\n\n\n### Output List-Columns From Other Functions\n\n- `dplyr::mutate()`, `transmute()`, and `summarise()` will output list-columns if they return a list.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n mtcars |>\n group_by(cyl) |>\n summarise(q = list(quantile(mpg)))\n ```\n :::\n\n\n### Reshape Nested Data\n\n- `unnest(data, cols, ..., keep_empty = FALSE)`: Flatten nested columns back to regular columns.\n The inverse of `nest()`.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n n_storms |> unnest(data)\n ```\n :::\n\n\n- `unnest_longer(data, col, values_to = NULL, indices_to = NULL)`: Turn each element of a list-column into a row.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n starwars |>\n select(name, films) |>\n unnest_longer(films)\n ```\n :::\n\n\n- `unnest_wider(data, col)`: Turn each element of a list-column into a regular column.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n starwars |>\n select(name, films) |>\n unnest_wider(films, names_sep = \"_\")\n ```\n :::\n\n\n- `hoist(.data, .col, ..., remove = TRUE)`: Selectively pull list components out into their own top-level columns.\n Uses `purrr::pluck()` syntax for selecting from lists.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n starwars |>\n select(name, films) |>\n hoist(films, first_film = 1, second_film = 2)\n ```\n :::\n\n\n### Transform Nested Data\n\nA vectorized function takes a vector, transforms each element in parallel, and returns a vector of the same length.\nBy themselves vectorized functions cannot work with lists, such as list-columns.\n\n- `dplyr::rowwise(.data, ...)`: Group data so that each row is one group, and within the groups, elements of list-columns appear directly (accessed with `[[`), not as lists of length one.\n **When you use rowwise(), dplyr functions will seem to apply functions to list-columns in a vectorized fashion.**\n\n- Apply a function to a list-column and **create a new list-column.** In this example, `dim()` returns two values per row and so is wrapped with `list()` to tell `mutate()` to create a list-column.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n n_storms |>\n rowwise() |>\n mutate(n = list(dim(data))) # dim() returns two values per row, wrap with list to tell mutate to create a list-column\n ```\n :::\n\n\n- Apply a function to a list-column and **create a regular column.** In this example, `nrow()` returns one integer per row.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n n_storms |>\n rowwise() |>\n mutate(n = nrow(data)) # nrow() returns one integer per row\n ```\n :::\n\n\n- Collapse **multiple list-columns** into a single list-column.\n In this example, `append()` returns a list for each row, so col type must be list.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n starwars |>\n rowwise() |>\n mutate(transport = list(append(vehicles, starships))) # append() returns a list for each row, so col type must be list\n ```\n :::\n\n\n- Apply a function to **multiple list-columns.** In this example, `length()` returns one integer per row.\n\n\n ::: {.cell}\n \n ```{.r .cell-code}\n starwars |>\n rowwise() |>\n mutate(n_transports = length(c(vehicles, starships)))\n # length() returns one integer per row\n ```\n :::\n\n\n- See **purrr** package for more list functions.\n\n------------------------------------------------------------------------\n\nCC BY SA Posit Software, PBC • [info\\@posit.co](mailto:info@posit.co) • [posit.co](https://posit.co)\n\nLearn more at [tidyr.tidyverse.org](https://tidyr.tidyverse.org).\n\nUpdated: 2023-06.\n\n\n::: {.cell}\n\n```{.r .cell-code}\npackageVersion(\"tidyr\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '1.3.0'\n```\n:::\n\n```{.r .cell-code}\npackageVersion(\"tibble\")\n```\n\n::: {.cell-output .cell-output-stdout}\n```\n[1] '3.2.1'\n```\n:::\n:::\n\n\n------------------------------------------------------------------------\n", "supporting": [], "filters": [ "rmarkdown/pagebreak.lua" diff --git a/contributed-cheatsheets.qmd b/contributed-cheatsheets.qmd index 6ca15a2d..f06517da 100644 --- a/contributed-cheatsheets.qmd +++ b/contributed-cheatsheets.qmd @@ -6,111 +6,111 @@ Cheatsheets contributed by the community. Several of these cheatsheets also have non-English translations, available on the [Translated Cheatsheets](translations.html) page. ::: {layout-ncol="3" layout-valign="bottom"} -[![arrow](pngs/arrow.png)](arrow.pdf) +[![arrow](pngs/arrow.png){alt="Download arrow pdf cheatsheet"}](arrow.pdf) -[![Base R](pngs/base-r.png)](base-r.pdf) +[![Base R](pngs/base-r.png){alt="Download Base R pdf cheatsheet"}](base-r.pdf) -[![bayesplot](pngs/bayesplot.png)](bayesplot.pdf) +[![bayesplot](pngs/bayesplot.png){alt="Download bayesplot pdf cheatsheet"}](bayesplot.pdf) -[![bcea](pngs/bcea.png)](bcea.pdf) +[![bcea](pngs/bcea.png){alt="Download bcea pdf cheatsheet"}](bcea.pdf) -[![caret](pngs/caret.png)](caret.pdf) +[![caret](pngs/caret.png){alt="Download caret pdf cheatsheet"}](caret.pdf) -[![cartography](pngs/cartography.png)](cartography.pdf) +[![cartography](pngs/cartography.png){alt="Download cartography pdf cheatsheet"}](cartography.pdf) -[![collapse](pngs/collapse.png)](collapse.pdf) +[![collapse](pngs/collapse.png){alt="Download collapse pdf cheatsheet"}](collapse.pdf) -[![datatable](pngs/datatable.png)](datatable.pdf) +[![datatable](pngs/datatable.png){alt="Download datatable pdf cheatsheet"}](datatable.pdf) -[![declaredesign](pngs/declaredesign.png)](declaredesign.pdf) +[![declaredesign](pngs/declaredesign.png){alt="Download declaredesign pdf cheatsheet"}](declaredesign.pdf) -[![distr6](pngs/distr6.png)](distr6.pdf) +[![distr6](pngs/distr6.png){alt="Download distr6 pdf cheatsheet"}](distr6.pdf) -[![estimatr](pngs/estimatr.png)](estimatr.pdf) +[![estimatr](pngs/estimatr.png){alt="Download estimatr pdf cheatsheet"}](estimatr.pdf) -[![eurostat](pngs/eurostat.png)](eurostat.pdf) +[![eurostat](pngs/eurostat.png){alt="Download eurostat pdf cheatsheet"}](eurostat.pdf) -[![gganimate](pngs/gganimate.png)](gganimate.pdf) +[![gganimate](pngs/gganimate.png){alt="Download gganimate pdf cheatsheet"}](gganimate.pdf) -[![Git & GitHub](pngs/git-github.png)](git-github.pdf) +[![Git & GitHub](pngs/git-github.png){alt="Download Git & GitHub pdf cheatsheet"}](git-github.pdf) -[![golem](pngs/golem.png)](golem.pdf) +[![golem](pngs/golem.png){alt="Download golem pdf cheatsheet"}](golem.pdf) -[![gtsummary](pngs/gtsummary.png)](gtsummary.pdf) +[![gtsummary](pngs/gtsummary.png){alt="Download gtsummary pdf cheatsheet"}](gtsummary.pdf) -[![gwasrapidd](pngs/gwasrapidd.png)](gwasrapidd.pdf) +[![gwasrapidd](pngs/gwasrapidd.png){alt="Download gwasrapidd pdf cheatsheet"}](gwasrapidd.pdf) -[![h2o](pngs/h2o.png)](h2o.pdf) +[![h2o](pngs/h2o.png){alt="Download h2o pdf cheatsheet"}](h2o.pdf) -[![How big is your graph?](pngs/how-big-is-your-graph.png)](how-big-is-your-graph.pdf) +[![How big is your graph?](pngs/how-big-is-your-graph.png){alt="Download How big is your graph? pdf cheatsheet"}](how-big-is-your-graph.pdf) -[![imputeTS](pngs/imputeTS.png)](imputeTS.pdf) +[![imputeTS](pngs/imputeTS.png){alt="Download imputeTS pdf cheatsheet"}](imputeTS.pdf) -[![jfa](pngs/jfa.png)](jfa.pdf) +[![jfa](pngs/jfa.png){alt="Download jfa pdf cheatsheet"}](jfa.pdf) -[![labelled](pngs/labelled.png)](labelled.pdf) +[![labelled](pngs/labelled.png){alt="Download labelled pdf cheatsheet"}](labelled.pdf) -[![leaflet](pngs/leaflet.png)](leaflet.pdf) +[![leaflet](pngs/leaflet.png){alt="Download leaflet pdf cheatsheet"}](leaflet.pdf) -[![Machine learning modelling in R](pngs/Machine%20Learning%20Modelling%20in%20R.png)](Machine%20Learning%20Modelling%20in%20R.pdf) +[![Machine learning modelling in R](pngs/Machine%20Learning%20Modelling%20in%20R.png){alt="Download Machine Learning Modelling in R pdf cheatsheet"}](Machine%20Learning%20Modelling%20in%20R.pdf) -[![mapsf](pngs/mapsf.png)](mapsf.pdf) +[![mapsf](pngs/mapsf.png){alt="Download mapsf pdf cheatsheet"}](mapsf.pdf) -[![mlr](pngs/mlr.png)](mlr.pdf) +[![mlr](pngs/mlr.png){alt="Download mlr pdf cheatsheet"}](mlr.pdf) -[![mosaic](pngs/mosaic.png)](mosaic.pdf) +[![mosaic](pngs/mosaic.png){alt="Download mosaic pdf cheatsheet"}](mosaic.pdf) -[![nardl](pngs/nardl.png)](nardl.pdf) +[![nardl](pngs/nardl.png){alt="Download nardl pdf cheatsheet"}](nardl.pdf) -[![nimble](pngs/nimble.png)](nimble.pdf) +[![nimble](pngs/nimble.png){alt="Download nimble pdf cheatsheet"}](nimble.pdf) -[![oSCR](pngs/oSCR.png)](oSCR.pdf) +[![oSCR](pngs/oSCR.png){alt="Download oSCR pdf cheatsheet"}](oSCR.pdf) -[![overviewR](pngs/overviewR.png)](overviewR.pdf) +[![overviewR](pngs/overviewR.png){alt="Download overviewR pdf cheatsheet"}](overviewR.pdf) -[![packagefinder](pngs/packagefinder.png)](packagefinder.pdf) +[![packagefinder](pngs/packagefinder.png){alt="Download packagefinder pdf cheatsheet"}](packagefinder.pdf) -[![Parallel computation](pngs/parallel_computation.png)](parallel_computation.pdf) +[![Parallel computation](pngs/parallel_computation.png){alt="Download Parallel computation pdf cheatsheet"}](parallel_computation.pdf) -[![quanteda](pngs/quanteda.png)](quanteda.pdf) +[![quanteda](pngs/quanteda.png){alt="Download quanteda pdf cheatsheet"}](quanteda.pdf) -[![quincunx](pngs/quincunx.png)](quincunx.pdf) +[![quincunx](pngs/quincunx.png){alt="Download quincunx pdf cheatsheet"}](quincunx.pdf) -[![randomizr](pngs/randomizr.png)](randomizr.pdf) +[![randomizr](pngs/randomizr.png){alt="Download randomizr pdf cheatsheet"}](randomizr.pdf) -[![Regular Expressions](pngs/regular-expressions.png)](regex.pdf) +[![Regular Expressions](pngs/regular-expressions.png){alt="Download Regular Expressions pdf cheatsheet"}](regex.pdf) -[![rphylopic](pngs/rphylopic.png)](rphylopic.pdf) +[![rphylopic](pngs/rphylopic.png){alt="Download rphylopic pdf cheatsheet"}](rphylopic.pdf) -[![SamplingStrata](pngs/SamplingStrata.png)](SamplingStrata.pdf) +[![SamplingStrata](pngs/SamplingStrata.png){alt="Download SamplingStrata pdf cheatsheet"}](SamplingStrata.pdf) -[![SAS \<-\> R](pngs/sas-r.png)](sas-r.pdf) +[![SAS \<-\> R](pngs/sas-r.png){alt="Download SAS \<-\> R pdf cheatsheet"}](sas-r.pdf) -[![sf](pngs/sf.png)](sf.pdf) +[![sf](pngs/sf.png){alt="Download sf pdf cheatsheet"}](sf.pdf) -[![sjmisc](pngs/sjmisc.png)](sjmisc.pdf) +[![sjmisc](pngs/sjmisc.png){alt="Download sjmisc pdf cheatsheet"}](sjmisc.pdf) -[![slackr](pngs/slackr.png)](slackr.pdf) +[![slackr](pngs/slackr.png){alt="Download slackr pdf cheatsheet"}](slackr.pdf) -[![stata2r](pngs/stata2r.png)](stata2r.pdf) +[![stata2r](pngs/stata2r.png){alt="Download stata2r pdf cheatsheet"}](stata2r.pdf) -[![survminer](pngs/survminer.png)](survminer.pdf) +[![survminer](pngs/survminer.png){alt="Download survminer pdf cheatsheet"}](survminer.pdf) -[![R syntax comparison](pngs/syntax.png)](syntax.pdf) +[![R syntax comparison](pngs/syntax.png){alt="Download R syntax comparison pdf cheatsheet"}](syntax.pdf) -[![teachR](pngs/teachR.png)](teachR.pdf) +[![teachR](pngs/teachR.png){alt="Download teachR pdf cheatsheet"}](teachR.pdf) -[![tidyeval](pngs/tidyeval.png)](tidyeval.pdf) +[![tidyeval](pngs/tidyeval.png){alt="Download tidyeval pdf cheatsheet"}](tidyeval.pdf) -[![time-series](pngs/time-series.png)](time-series.pdf) +[![time-series](pngs/time-series.png){alt="Download time-series pdf cheatsheet"}](time-series.pdf) -[![torch](pngs/torch.png)](torch.pdf) +[![torch](pngs/torch.png){alt="Download torch pdf cheatsheet"}](torch.pdf) -[![tsbox](pngs/tsbox.png)](tsbox.pdf) +[![tsbox](pngs/tsbox.png){alt="Download tsbox pdf cheatsheet"}](tsbox.pdf) -[![vegan](pngs/vegan.png)](vegan.pdf) +[![vegan](pngs/vegan.png){alt="Download vegan pdf cheatsheet"}](vegan.pdf) -[![vtree](pngs/vtree.png)](vtree.pdf) +[![vtree](pngs/vtree.png){alt="Download vtree pdf cheatsheet"}](vtree.pdf) -[![xplain](pngs/xplain.png)](xplain.pdf) +[![xplain](pngs/xplain.png){alt="Download xplain pdf cheatsheet"}](xplain.pdf) ::: diff --git a/html/common.R b/html/common.R index 592538b7..81994c93 100644 --- a/html/common.R +++ b/html/common.R @@ -23,7 +23,7 @@ use_cheatsheet_logo <- function(pkg, geometry = "240x278", alt = "", retina = TR cat(glue::glue( ' - \"{alt}\" + {alt}

' )) @@ -34,7 +34,7 @@ pdf_preview_link <- function(sheet_name) { '

Download PDF

- +


' diff --git a/html/data-import.qmd b/html/data-import.qmd index e5242925..e6fc0997 100644 --- a/html/data-import.qmd +++ b/html/data-import.qmd @@ -1,7 +1,6 @@ --- title: "Data import with the tidyverse :: Cheatsheet" description: " " -image-alt: "" execute: eval: true output: false @@ -13,7 +12,10 @@ execute: #| echo: false #| column: margin source("common.R") -use_cheatsheet_logo("readr") +use_cheatsheet_logo( + "readr", + alt = "Hex logo for readr - a white document icon going dowards into a dark blue funnel, with a white icon of a data table coming out the narrow end, all on a blue background." + ) sheet_name <- tools::file_path_sans_ext(knitr::current_input()) pdf_preview_link(sheet_name) translation_list(sheet_name) @@ -50,7 +52,7 @@ library(readr) See `?read_delim`. -```r +``` r read_*( file, col_names = TRUE, col_types = NULL, col_select = NULL, @@ -272,7 +274,7 @@ write_file("A,B,C\n7,8,9\nNA,11,12", file = "file3.csv") ### Save data with readr -```r +``` r write_*( x, file, na = "NA", @@ -323,20 +325,20 @@ Each column type has a function and corresponding string abbreviation. - Hide col spec message: - ```r + ``` r read_*(file, show_col_types = FALSE) ``` - Select columns to import: Use names, position, or selection helpers. - ```r + ``` r read_*(file, col_select = c(age, earn)) ``` - Guess column types: To guess a column type, `read_ *()` looks at the first 1000 rows of data. Increase with `guess_max`. - ```r + ``` r read_*(file, guess_max = Inf) ``` diff --git a/html/data-transformation.qmd b/html/data-transformation.qmd index 4ff9963b..6050dbde 100644 --- a/html/data-transformation.qmd +++ b/html/data-transformation.qmd @@ -13,7 +13,10 @@ execute: #| echo: false #| column: margin source("common.R") -use_cheatsheet_logo("dplyr") +use_cheatsheet_logo( + "dplyr", + alt = "Hex logo for dplyr - three different brightly coloured cartoon pairs of pliers that appear as spaceships flying through a black background, with coloured spots representing stars and planets." + ) sheet_name <- tools::file_path_sans_ext(knitr::current_input()) pdf_preview_link(sheet_name) translation_list(sheet_name) diff --git a/html/data-visualization.qmd b/html/data-visualization.qmd index b8932783..4dc5fb29 100644 --- a/html/data-visualization.qmd +++ b/html/data-visualization.qmd @@ -1,8 +1,6 @@ --- title: "Data visualization with ggplot2 :: Cheat Sheet" description: " " -image: "images/logo-ggplot2.png" -image-alt: "Hex logo for ggplot2 - Six points following an overall increasing trend filled with colors going from light blue to dark blue, connected with a black line, on a light gray background with white grid lines." execute: eval: true output: false @@ -15,7 +13,10 @@ execute: #| column: margin source("common.R") -use_cheatsheet_logo("ggplot2", alt = "Hex logo for ggplot2 - Six points following an overall increasing trend filled with colors going from light blue to dark blue, connected with a black line, on a light gray background with white grid lines.") +use_cheatsheet_logo( + "ggplot2", + alt = "Hex logo for ggplot2 - Six points following an overall increasing trend filled with colors going from light blue to dark blue, connected with a black line, on a light gray background with white grid lines." +) sheet_name <- tools::file_path_sans_ext(knitr::current_input()) pdf_preview_link(sheet_name) diff --git a/html/factors.qmd b/html/factors.qmd index a5c6bc44..cdc707ae 100644 --- a/html/factors.qmd +++ b/html/factors.qmd @@ -13,7 +13,10 @@ execute: #| echo: false #| column: margin source("common.R") -use_cheatsheet_logo("forcats") +use_cheatsheet_logo( + "forcats", + alt = "Hex logo for forcats - drawing of four black cats lounging in a cardboard box. On one side of the box it says 'for' and on the adjacent side is says 'cats'." +) sheet_name <- tools::file_path_sans_ext(knitr::current_input()) pdf_preview_link(sheet_name) translation_list(sheet_name) diff --git a/html/keras.qmd b/html/keras.qmd index 0f6d417c..9d38b240 100644 --- a/html/keras.qmd +++ b/html/keras.qmd @@ -14,7 +14,9 @@ execute: #| echo: false #| column: margin source("common.R") -use_cheatsheet_logo("tensorflow") +use_cheatsheet_logo( + "tensorflow", + alt = "Hex logo for tensorflow - A red hexagon with a stylized 'TFR' (denoting TensorFlow for R) in a lighter shade of red, with the 'F' joined to the 'R'.") sheet_name <- tools::file_path_sans_ext(knitr::current_input()) pdf_preview_link(sheet_name) translation_list(sheet_name) diff --git a/html/lubridate.qmd b/html/lubridate.qmd index 1c0e7fc7..9677153b 100644 --- a/html/lubridate.qmd +++ b/html/lubridate.qmd @@ -13,7 +13,9 @@ execute: #| echo: false #| column: margin source("common.R") -use_cheatsheet_logo("lubridate") +use_cheatsheet_logo( + "lubridate", + alt = "Hex logo for lubridate - a white calendar on a green background, with a clock superimposed on it. 'lubdridate' is written in white across the bottom.") sheet_name <- tools::file_path_sans_ext(knitr::current_input()) pdf_preview_link(sheet_name) translation_list(sheet_name) diff --git a/html/package-development.qmd b/html/package-development.qmd index b1353ced..8a0dfb8a 100644 --- a/html/package-development.qmd +++ b/html/package-development.qmd @@ -13,7 +13,9 @@ execute: #| echo: false #| column: margin source("common.R") -use_cheatsheet_logo("devtools") +use_cheatsheet_logo( + "devtools", + alt = "Hex logo for devtools - The bottom part of a lowercase 'd' in black, in a hexagonal shape slightly inside the boundary of the hexagonal logo. The background is filled in three shades of blue. 'devtools' is written across the front in white.") sheet_name <- tools::file_path_sans_ext(knitr::current_input()) pdf_preview_link(sheet_name) translation_list(sheet_name) diff --git a/html/plumber.qmd b/html/plumber.qmd index 6c94d3ba..8c3e39d1 100644 --- a/html/plumber.qmd +++ b/html/plumber.qmd @@ -13,7 +13,10 @@ execute: #| echo: false #| column: margin source("common.R") -use_cheatsheet_logo("plumber") +use_cheatsheet_logo( + "plumber", + alt = "Hex logo for plumber - the word 'plumber' written in green, where the letters are depicted as water pipes, which connect to the border of the logo. The background is a series of criss-crossing pipes in shades of black and grey." + ) sheet_name <- tools::file_path_sans_ext(knitr::current_input()) pdf_preview_link(sheet_name) translation_list(sheet_name) @@ -37,7 +40,7 @@ Requests and responses are specially formatted text containing details and data `Request Body` -\> Message body -``` +``` curl -v "http://httpbin.org/get" #> GET / get HTTP/1.1 diff --git a/html/purrr.qmd b/html/purrr.qmd index 1df2a6f8..b6336051 100644 --- a/html/purrr.qmd +++ b/html/purrr.qmd @@ -13,7 +13,9 @@ execute: #| echo: false #| column: margin source("common.R") -use_cheatsheet_logo("purrr") +use_cheatsheet_logo( + "purrr", + alt = "Hex logo for purrr - a simple sketch of a sleeping cat nestled into the bottom of the black border of the hexagon. 'purrr' is written across the top in black.") sheet_name <- tools::file_path_sans_ext(knitr::current_input()) pdf_preview_link(sheet_name) translation_list(sheet_name) diff --git a/html/reticulate.qmd b/html/reticulate.qmd index f5d14c57..9ec74da6 100644 --- a/html/reticulate.qmd +++ b/html/reticulate.qmd @@ -14,7 +14,10 @@ execute: #| echo: false #| column: margin source("common.R") -use_cheatsheet_logo("reticulate") +use_cheatsheet_logo( + "reticulate", + alt = "Hex logo for reticulate - a navy blue background with a light-blue and yellow snake semi-coiled across the foreground. 'reticulate' is written across the bottom in white." + ) sheet_name <- tools::file_path_sans_ext(knitr::current_input()) pdf_preview_link(sheet_name) translation_list(sheet_name) diff --git a/html/rmarkdown.qmd b/html/rmarkdown.qmd index b7ef0698..0f04b14e 100644 --- a/html/rmarkdown.qmd +++ b/html/rmarkdown.qmd @@ -13,7 +13,9 @@ execute: #| echo: false #| column: margin source("common.R") -use_cheatsheet_logo("rmarkdown") +use_cheatsheet_logo( + "rmarkdown", + alt = "Hex logo for rmarkdown - a dark blue background with a teal border. 'rmarkdown' is written across the bottom in light teal, and there is a quill pen above the word, with the tip pointing to the first 'r'.") sheet_name <- tools::file_path_sans_ext(knitr::current_input()) pdf_preview_link(sheet_name) translation_list(sheet_name) diff --git a/html/rstudio-ide.qmd b/html/rstudio-ide.qmd index d2810604..713807a5 100644 --- a/html/rstudio-ide.qmd +++ b/html/rstudio-ide.qmd @@ -14,7 +14,10 @@ engine: knitr #| echo: false #| column: margin source("common.R") -use_cheatsheet_logo("RStudio") +use_cheatsheet_logo( + "RStudio", + alt = "Hex logo for the RStudio IDE - A light blue hexagon with the word 'RStudio' in the middle. The 'R' is blue in the centre of a solid white circle, while 'Studio' is written in white on the blue background." + ) sheet_name <- tools::file_path_sans_ext(knitr::current_input()) pdf_preview_link(sheet_name) translation_list(sheet_name) diff --git a/html/shiny.qmd b/html/shiny.qmd index 67d0bb9e..bc2e25d0 100644 --- a/html/shiny.qmd +++ b/html/shiny.qmd @@ -13,7 +13,10 @@ execute: #| echo: false #| column: margin source("common.R") -use_cheatsheet_logo("shiny") +use_cheatsheet_logo( + "shiny", + alt = "Hex logo for Shiny - A blue hexagon with the word 'Shiny' written in white in a flowing cursive font. The tail of the 'y' flows back to the left to underline the word." + ) sheet_name <- tools::file_path_sans_ext(knitr::current_input()) pdf_preview_link(sheet_name) translation_list(sheet_name) diff --git a/html/strings.qmd b/html/strings.qmd index 2a9eef8d..a3e36b64 100644 --- a/html/strings.qmd +++ b/html/strings.qmd @@ -13,7 +13,9 @@ execute: #| echo: false #| column: margin source("common.R") -use_cheatsheet_logo("stringr") +use_cheatsheet_logo( + "stringr", + alt = "Hex logo for stringr - a green hexagon with a white violin in the centre, above the word 'stringr' in white.") sheet_name <- tools::file_path_sans_ext(knitr::current_input()) pdf_preview_link(sheet_name) translation_list(sheet_name) @@ -468,16 +470,16 @@ see <- function(rx) str_view_all("abc ABC 123\t.!?\\(){}\n", rx) `anchor <- function(rx) str_view_all("aaa", rx)` +------------+-----------------+----------------+--------------------------------------+ -| regexp | matches | example | example output\ | -| | | | (highlighted characters are in \<\>) | +| regexp | matches | example | example output\ | +| | | | (highlighted characters are in \<\>) | +============+=================+================+======================================+ -| `^a` | start of string | `anchor("^a")` | ``` | -| | | | aa | -| | | | ``` | +| `^a` | start of string | `anchor("^a")` | ``` | +| | | | aa | +| | | | ``` | +------------+-----------------+----------------+--------------------------------------+ -| `a$` | end of string | `anchor("a$")` | ``` | -| | | | aa | -| | | | ``` | +| `a$` | end of string | `anchor("a$")` | ``` | +| | | | aa | +| | | | ``` | +------------+-----------------+----------------+--------------------------------------+ : Anchors diff --git a/html/tidyr.qmd b/html/tidyr.qmd index b3c44ba1..1101e681 100644 --- a/html/tidyr.qmd +++ b/html/tidyr.qmd @@ -13,7 +13,9 @@ execute: #| echo: false #| column: margin source("common.R") -use_cheatsheet_logo("tidyr") +use_cheatsheet_logo( + "tidyr", + alt = "Hex logo for tidyr - three different brightly coloured cartoon brooms that appear as spaceships flying through a black background, with coloured spots representing stars and planets.") sheet_name <- tools::file_path_sans_ext(knitr::current_input()) pdf_preview_link(sheet_name) translation_list(sheet_name)