### Install yaml12 Development Version from GitHub Source: https://posit-dev.github.io/r-yaml12/llms.txt Installs the development version of the yaml12 package from GitHub using the 'pak' package manager. ```r # install.packages("pak") pak::pak("posit-dev/r-yaml12") ``` -------------------------------- ### YAML Mapping Example Source: https://posit-dev.github.io/r-yaml12/articles/yaml-2-minute-intro Parses a simple YAML mapping into a named R list. ```yaml foo: 1 bar: true ``` -------------------------------- ### YAML Sequence Example (Dash Notation) Source: https://posit-dev.github.io/r-yaml12/articles/yaml-2-minute-intro Parses a YAML sequence using dash notation into an R character vector. ```yaml - cat - dog ``` -------------------------------- ### Install yaml12 from CRAN Source: https://posit-dev.github.io/r-yaml12/llms.txt Installs the yaml12 package from the Comprehensive R Archive Network (CRAN). ```r install.packages("yaml12") ``` -------------------------------- ### Setup benchmark objects Source: https://posit-dev.github.io/r-yaml12/articles/benchmarks Generates a list of objects of increasing size for benchmarking write performance. Uses `lapply` to create objects with varying numbers of repetitions. ```r objs <- lapply(2^(1:15), function(n) rep(list(mixed_node), n)) ``` -------------------------------- ### YAML Comments Example Source: https://posit-dev.github.io/r-yaml12/articles/yaml-2-minute-intro Demonstrates YAML comments (whole-line, inline, trailing) which are ignored by the parser. ```yaml # Whole-line comment title: example # inline comment items: [a, b] # trailing comment ``` -------------------------------- ### YAML Sequence Example (JSON Array Notation) Source: https://posit-dev.github.io/r-yaml12/articles/yaml-2-minute-intro Parses a YAML sequence using JSON array notation into an R character vector. ```yaml [cat, dog] ``` -------------------------------- ### YAML Mapping Example (JSON Object Notation) Source: https://posit-dev.github.io/r-yaml12/articles/yaml-2-minute-intro Parses a YAML mapping using JSON object notation into an R list. ```yaml {a: true} ``` -------------------------------- ### YAML Nested Sequence Example Source: https://posit-dev.github.io/r-yaml12/articles/yaml-2-minute-intro Parses a YAML sequence with nested mappings, converting it into a nested R list structure. ```yaml - name: cat toys: [string, box] - name: dog toys: [ball, bone] ``` ```r list( list(name = "cat", toys = c("string", "box")), list(name = "dog", toys = c("ball", "bone")) ) ``` -------------------------------- ### R Parsing of YAML Document Source: https://posit-dev.github.io/r-yaml12/articles/yaml-2-minute-intro Shows the R list structure resulting from parsing the example YAML document using default settings. ```r list( doc = list( pets = c("cat", "dog"), numbers = c(1, 2.5, 16, Inf, NA_real_), integers = c(1L, 2L, 3L, 16L, NA_integer_), flags = list(enabled = TRUE, label = "on"), literal = "hello\nworld\n", folded = "hello world\n", quoted = c("line\nbreak", "quote: 'here'"), plain = c("yes", "no"), mixed = list("won't simplify", 123L, TRUE) ) ) ``` -------------------------------- ### YAML Nested Mapping Example Source: https://posit-dev.github.io/r-yaml12/articles/yaml-2-minute-intro Parses a YAML mapping with nested key-value pairs into a nested R list. ```yaml settings: simplify: true max_items: 3 ``` -------------------------------- ### Write a list to a YAML file or stdout Source: https://posit-dev.github.io/r-yaml12/reference/format_yaml Writes an R list to a YAML formatted file or standard output. Includes document start and end markers. If `path` is NULL, output goes to stdout. ```r write_yaml(list(foo = 1, bar = list(2, "baz"))) #> --- #> foo: 1 #> bar: #> - 2 #> - baz #> ... ``` -------------------------------- ### YAML Quoted Scalar Example Source: https://posit-dev.github.io/r-yaml12/articles/yaml-2-minute-intro Parses quoted scalars, demonstrating interpretation of escape sequences like \n and \" within double quotes, and literal handling of '' within single quotes. ```yaml ["line\nbreak", "quote: \"here\""] ``` ```yaml ['line\nbreak', 'quote: \'\'here\'\''] ``` -------------------------------- ### Write Multiple YAML Documents Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Use `multi = TRUE` to write a list of R objects as a YAML document stream, with documents separated by '---'. `write_yaml()` includes start and end markers. ```r write_yaml(list("foo", "bar")) #> --- #> - foo #> - bar #> ... write_yaml(list("foo", "bar"), multi = TRUE) #> --- #> foo #> --- #> bar #> ... ``` -------------------------------- ### write_yaml Source: https://posit-dev.github.io/r-yaml12/reference/format_yaml Writes an R object as a YAML 1.2 stream to a file or standard output. It always includes document start and end markers. ```APIDOC ## write_yaml(value, path = NULL, multi = FALSE) ### Description Writes a YAML stream to a file or stdout. It always emits document start (`---`) markers and a final end (`...`) marker. If `multi` is `TRUE`, it treats the `value` as a list of YAML documents and encodes a stream. ### Arguments * `value`: Any R object composed of lists, atomic vectors, and scalars. * `path`: Scalar string file path to write YAML to. When `NULL` (the default), write to R's standard output connection. * `multi`: When `TRUE`, treat `value` as a list of YAML documents and encode a stream. ### Value Invisibly returns `value`. ### Examples ```r write_yaml(list(foo = 1, bar = list(2, "baz"))) #> --- #> foo: 1 #> bar: #> - 2 #> - baz #> ... write_yaml(list("foo", "bar"), multi = TRUE) #> --- #> foo #> --- #> bar #> ... tagged <- structure("1 + 1", yaml_tag = "!expr") write_yaml(tagged) #> --- #> !expr 1 + 1 #> ... ``` ``` -------------------------------- ### Format an R object with a custom YAML tag Source: https://posit-dev.github.io/r-yaml12/reference/format_yaml Applies a custom YAML tag to an R object before formatting it as YAML. The `yaml_tag` attribute is used to specify the tag. This example also shows how to parse the resulting YAML back into an R object. ```r tagged <- structure("1 + 1", yaml_tag = "!expr") cat(tagged_yaml <- format_yaml(tagged), "\n") #> !expr 1 + 1 dput(parse_yaml(tagged_yaml)) #> structure("1 + 1", yaml_tag = "!expr") ``` -------------------------------- ### Read and Write YAML Files Source: https://posit-dev.github.io/r-yaml12/llms.txt Demonstrates writing an R list to a YAML file and then reading it back. Includes handling of multi-document streams. ```r value_out <- list(alpha = 1L, nested = c(TRUE, NA)) write_yaml(value_out, "my.yaml") value_in <- read_yaml("my.yaml") stopifnot(identical(value_out, value_in)) # Multi-document streams docs_out <- list(list(foo = 1L), list(bar = c(2L, NA))) write_yaml(docs_out, "my-multi.yaml", multi = TRUE) docs_in <- read_yaml("my-multi.yaml", multi = TRUE) stopifnot(identical(docs_in, docs_out)) ``` -------------------------------- ### Parsing YAML with Core Schema Tags Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Demonstrates how different core schema tags for strings resolve to the same internal representation and parse identically in R. ```r ' - foo - !!str foo - ! foo ' |> parse_yaml() |> dput() #> c("foo", "foo", "foo") ``` -------------------------------- ### Read YAML from a file and keep sequences as lists Source: https://posit-dev.github.io/r-yaml12/reference/parse_yaml Shows how to read YAML content from a file using `read_yaml()` and preserve sequences as R lists by setting `simplify = FALSE`. Uses `str` for output. ```r path <- tempfile(fileext = ".yaml") writeLines("alpha: [true, null]\nbeta: 3.5", path) str(read_yaml(path, simplify = FALSE)) #> List of 2 #> $ alpha:List of 2 #> ..$ : logi TRUE #> ..$ : NULL #> $ beta : num 3.5 ``` -------------------------------- ### Handling tagged sequences and mappings Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Demonstrates how handlers receive tagged sequences as R vectors or lists and tagged mappings as named R lists. The handler functions must validate the received structure. ```r handlers <- list( "!some_seq_tag" = function(x) { stopifnot(identical(x, c("a", "b"))) "some handled value" }, "!some_map_tag" = function(x) { stopifnot(identical(x, list(key1 = 1L, key2 = 2L))) "some other handled value" } ) yaml_tagged_containers <- " - !some_seq_tag [a, b] - !some_map_tag {key1: 1, key2: 2} " str(parse_yaml(yaml_tagged_containers, handlers = handlers)) ``` -------------------------------- ### Parsing YAML with Complex Keys Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Illustrates parsing YAML with complex keys, including sequences and mappings, using the explicit mapping-key indicator `?`. ```yaml ? [a, b] : value with a sequence key ? {x: 1, y: 2} : value with a mapping key ``` -------------------------------- ### Write Results (Detailed) Source: https://posit-dev.github.io/r-yaml12/articles/benchmarks Iterates through benchmark results, printing plots with size labels and detailed summaries. Use this to inspect individual benchmark outcomes. ```r invisible(lapply(write_results, \(result) { print(plot(result) + ggplot2::ggtitle(scales::label_bytes()(as.numeric(result$obj_size[1])))) print(summary(result, filter_gc = FALSE)) })) ``` -------------------------------- ### Summarize write results Source: https://posit-dev.github.io/r-yaml12/articles/benchmarks Combines the benchmark results into a data frame and converts the expression names to factors for easier plotting. Uses `bind_rows` and `mutate` for data manipulation. ```r write_results_df <- bind_rows(write_results) | mutate(expression = as.factor(sapply(expression, deparse1))) ``` -------------------------------- ### Run write performance benchmark Source: https://posit-dev.github.io/r-yaml12/articles/benchmarks Benchmarks the `write_yaml` function from both `yaml12` and `yaml` packages. It measures the execution time for writing objects of different sizes and stores the results. Includes a warning about GC filtering. ```r write_results <- lapply(objs, function(obj) { result <- bench::mark( yaml12::write_yaml(obj, nullfile()), yaml::write_yaml(obj, nullfile()), check = FALSE ) result$obj_size <- object.size(obj) result }) #> Warning: Some expressions had a GC in every iteration; so filtering is #> disabled. ``` -------------------------------- ### Parse YAML sequence as list using simplify=FALSE Source: https://posit-dev.github.io/r-yaml12/reference/parse_yaml Illustrates how to prevent simplification of YAML sequences to R atomic vectors by setting `simplify = FALSE`. Uses `str` to display the detailed structure. ```r str(parse_yaml("foo: [1, 2, 3, null]", simplify = FALSE)) #> List of 1 #> $ foo:List of 4 #> ..$ : int 1 #> ..$ : int 2 #> ..$ : int 3 #> ..$ : NULL ``` -------------------------------- ### Read and Plot Benchmark Results Source: https://posit-dev.github.io/r-yaml12/articles/benchmarks Iterates through a list of benchmark results, printing a plot of each result with its file size as the title and a detailed summary. This is useful for visualizing and analyzing performance across different file sizes. ```r invisible(lapply(read_results, \(result) { print(plot(result) + ggplot2::ggtitle(scales::label_bytes()(result$file_size[1]))) print(summary(result, filter_gc = FALSE)) })) ``` -------------------------------- ### Multiple handlers for different tags Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Shows how to define multiple handlers for different tags. Unmatched tags are preserved with their 'yaml_tag' attribute, and unused handlers are ignored. ```r handlers <- list( "!expr" = function(x) eval(str2lang(x), globalenv()), "!upper" = toupper, "!lower" = tolower # unused ) str(parse_yaml(handlers = handlers, " - !expr 1+1 - !upper r is awesome - !note this tag has no handler ")) ``` -------------------------------- ### Parsing YAML with Timestamp and Binary Tags Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Shows how YAML timestamp and binary tags are parsed into character strings with a 'yaml_tag' attribute by default. ```r yaml <- " - !!timestamp 2025-01-01 - !!timestamp 2025-01-01 21:59:43.10 -5 - !!binary UiBpcyBBd2Vzb21l " str(parse_yaml(yaml)) ``` -------------------------------- ### Format R Object to YAML with Custom Keys and Tags Source: https://posit-dev.github.io/r-yaml12/llms.txt Formats an R object into YAML, preserving custom tags and non-string keys. Demonstrates round-tripping capability. ```r obj <- list( seq = 1:2, map = list(key = "value"), tagged = structure("1 + 1", yaml_tag = "!expr"), keys = structure( list("a", "b", "c"), names = c("plain", "", ""), yaml_keys = list("plain", TRUE, structure("foo", yaml_tag = "!custom")) ) ) yaml <- format_yaml(obj) cat(yaml) #> seq: #> - 1 #> - 2 #> map: #> key: value #> tagged: !expr 1 + 1 #> keys: #> plain: a #> true: b #> !custom foo: c roundtripped <- parse_yaml(yaml) identical(obj, roundtripped) #> [1] TRUE ``` -------------------------------- ### Parsing a Single YAML Document Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Demonstrates parsing a YAML string with multiple documents when `multi` is set to `FALSE` (default), returning only the first document. ```r doc_stream <- " --- doc 1 --- doc 2 " parse_yaml(doc_stream) #> [1] "doc 1" ``` -------------------------------- ### Parse YAML with homogeneous sequence and null Source: https://posit-dev.github.io/r-yaml12/reference/parse_yaml Demonstrates parsing a YAML sequence that includes `null`, which maps to `NA` in R's atomic vectors. Uses `dput` for output. ```r dput(parse_yaml("foo: [1, 2, 3, null]")) #> list(foo = c(1L, 2L, 3L, NA)) ``` -------------------------------- ### Parse YAML with Global Tag Prefix Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Declare a global tag prefix using `%TAG ! ` to expand a bare `!` tag. ```r dput(parse_yaml(' %TAG ! tag:example.com,2024:widgets/ --- item: !gizmo foo ')) #> list(item = structure("foo", yaml_tag = "tag:example.com,2024:widgets/gizmo")) ``` -------------------------------- ### Format a list as YAML string Source: https://posit-dev.github.io/r-yaml12/reference/format_yaml Converts an R list to a YAML formatted string. Use cat() to print the string to the console. Demonstrates basic list and nested list formatting. ```r cat(format_yaml(list(foo = 1, bar = list(TRUE, NA)))) #> foo: 1 #> bar: #> - true #> - ~ ``` -------------------------------- ### Create YAML Document Source: https://posit-dev.github.io/r-yaml12/articles/benchmarks A function to generate a YAML file from a repeating list of nodes. It writes the YAML content to a temporary file and returns the file path. The size parameter controls the number of repetitions. ```r make_yaml_doc <- function(size = 1) { path <- tempfile(fileext = ".yaml") yaml12::write_yaml(rep(list(mixed_node), size), path) path } docs <- sapply(2^(1:15), make_yaml_doc) ``` -------------------------------- ### Parsing YAML with Mixed Key Types and `yaml_keys` Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Parses a YAML string containing a boolean key, a sequence key, and a mapping key, demonstrating how `yaml_keys` stores these complex keys in R. ```r yaml <- " true: true ? [a, b] : tuple ? {x: 1, y: 2} : map-key " str(parse_yaml(yaml)) #> List of 3 #> $ : logi TRUE #> $ : chr "tuple" #> $ : chr "map-key" #> - attr(*, "yaml_keys")=List of 3 #> ..$ : logi TRUE #> ..$ : chr [1:2] "a" "b" #> ..$ :List of 2 #> .. ..$ x: int 1 #> .. ..$ y: int 2 ``` -------------------------------- ### Parse YAML with TAG URIs Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Use the `!<...>` syntax to bypass handle resolution and use a tag URI directly. Content within `<...>` must be a valid URI. ```r dput(parse_yaml(' %TAG ! tag:example.com,2024:widgets/ --- item: ! foo ')) #> list(item = structure("foo", yaml_tag = "gizmo")) ``` -------------------------------- ### YAML 1.2 Document Structure Source: https://posit-dev.github.io/r-yaml12/articles/yaml-2-minute-intro Demonstrates the structure of a YAML 1.2 document, including nested collections, sequences, mappings, and block scalars. ```yaml doc: pets: - cat - dog numbers: [1, 2.5, 0x10, .inf, null] integers: [1, 2, 3, 0x10, null] flags: {enabled: true, label: on} literal: | hello world folded: > hello world quoted: - "line\nbreak" - 'quote: \'here\'' plain: [yes, no] mixed: [won't simplify, 123, true] ``` -------------------------------- ### Parse multiple YAML documents from a string Source: https://posit-dev.github.io/r-yaml12/reference/parse_yaml Demonstrates parsing a string containing multiple YAML documents separated by `---`. The `multi = TRUE` argument returns a list of all parsed documents. Uses `str` for output. ```r stream <- " --- first: 1 --- second: 2 " str(parse_yaml(stream, multi = TRUE)) #> List of 2 #> $ :List of 1 #> ..$ first: int 1 #> $ :List of 1 #> ..$ second: int 2 ``` -------------------------------- ### Load yaml12 Package Source: https://posit-dev.github.io/r-yaml12/articles/yaml-2-minute-intro Loads the yaml12 package for YAML parsing in R. ```r library(yaml12) ``` -------------------------------- ### Parse YAML with Tag Directives (%TAG) Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Use `%TAG` directives to declare tag handles at the top of a document, which automatically expand named tags. ```yaml %TAG !e! tag:example.com,2024:widgets/ --- item: !e!gizmo ``` ```r dput(parse_yaml(' %TAG !e! tag:example.com,2024:widgets/ --- item: !e!gizmo foo ')) #> list(item = structure("foo", yaml_tag = "tag:example.com,2024:widgets/gizmo")) ``` -------------------------------- ### Custom YAML Tag Handlers Source: https://posit-dev.github.io/r-yaml12/llms.txt Parses YAML with custom tags using provided handler functions. Demonstrates '!expr' and '!upper' tags. ```r yaml <- " - !upper [rust, r] - !expr 6 * 7 " handlers <- list( "!expr" = function(x) eval(str2lang(x), baseenv()), "!upper" = toupper ) parse_yaml(yaml, handlers = handlers) #> [[1]] #> [1] "RUST" "R" #> #> [[2]] #> [1] 42 ``` -------------------------------- ### Load Libraries Source: https://posit-dev.github.io/r-yaml12/articles/benchmarks Loads the dplyr and ggplot2 libraries. warn.conflicts = FALSE prevents messages about masked objects. ```r library(dplyr, warn.conflicts = FALSE) library(ggplot2) ``` -------------------------------- ### Parsing YAML with Custom Handlers Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Applies custom timestamp and binary handlers during YAML parsing to convert tagged strings into R Date, POSIXct, and raw objects. ```r yaml <- " - !!timestamp 2025-01-01 - !!timestamp 2025-01-01 21:59:43.10 -5 - !!binary UiBpcyBBd2Vzb21l " str(parse_yaml(yaml, handlers = list( "tag:yaml.org,2002:timestamp" = timestamp_handler, "tag:yaml.org,2002:binary" = binary_handler ))) #> List of 3 #> $ : Date[1:1], format: "2025-01-01" #> $ : POSIXct[1:1], format: "2025-01-01 21:59:43" #> $ : raw [1:12] 52 20 69 73 ... ``` -------------------------------- ### Plot Read Performance Source: https://posit-dev.github.io/r-yaml12/articles/benchmarks Generates a scatter plot with a smoothed line to visualize read performance. The x-axis represents file size (log scale), and the y-axis represents median run time. Different expressions (yaml12 vs. yaml) are colored differently. ```r read_results_df | ggplot(aes(x = file_size, y = median, color = expression)) + labs( y = "Median Run Time", x = "File Size", title = "Read Performance" ) + geom_point() + geom_smooth(linewidth = .5) + scale_x_log10(labels = scales::label_bytes()) + scale_y_continuous(trans = bench::bench_time_trans()) ``` -------------------------------- ### Write a list of documents as a YAML stream to stdout Source: https://posit-dev.github.io/r-yaml12/reference/format_yaml Writes an R list as a multi-document YAML stream to standard output. Each element of the list is treated as a separate YAML document, delimited by '---'. ```r write_yaml(list("foo", "bar"), multi = TRUE) #> --- #> foo #> --- #> bar #> ... ``` -------------------------------- ### YAML Plain Scalar Type Inference Source: https://posit-dev.github.io/r-yaml12/articles/yaml-2-minute-intro Demonstrates YAML's automatic type inference for plain scalars, including boolean, null, numeric, hexadecimal, octal, infinity, and NaN, with remaining values treated as strings. ```yaml [true, 123, 4.5e2, 0x10, 0o10, .inf, .nan, yes] ``` ```r list(TRUE, 123L, 450, 16L, 8L, Inf, NaN, "yes") ``` -------------------------------- ### YAML with Non-String Mapping Keys Source: https://posit-dev.github.io/r-yaml12/llms.txt Parses YAML with non-string keys (boolean, null, tagged string) and demonstrates how the 'yaml_keys' attribute captures original keys. ```r yaml <- " true: a null: b !custom foo: c " parsed <- parse_yaml(yaml) stopifnot(identical( parsed, structure( list("a", "b", "c"), names = c("", "", ""), yaml_keys = list(TRUE, NULL, structure("foo", yaml_tag = "!custom")) ) )) ``` -------------------------------- ### Parse YAML String into R List Source: https://posit-dev.github.io/r-yaml12/llms.txt Parses a YAML formatted string into an R list structure. Demonstrates basic YAML parsing. ```r library(yaml12) yaml <- " title: A modern YAML parser and emitter written in Rust properties: [fast, correct, safe, simple] sequences: simplify: true " doc <- parse_yaml(yaml) str(doc) #> List of 3 #> $ title : chr "A modern YAML parser and emitter written in Rust" #> $ properties: chr [1:4] "fast" "correct" "safe" "simple" #> $ sequences :List of 1 #> ..$ simplify: logi TRUE ``` -------------------------------- ### Parse YAML with mixed type sequence Source: https://posit-dev.github.io/r-yaml12/reference/parse_yaml Shows how mixed-type YAML sequences are parsed into R lists, as they do not simplify to atomic vectors. Uses `dput` for output. ```r dput(parse_yaml("[1, true, cat]")) #> list(1L, TRUE, "cat") ``` -------------------------------- ### Parse YAML with Anchors and Aliases Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features yaml12 resolves anchors (`&id`) and aliases (`*id`) before returning R objects, allowing nodes to be named and reused. ```r str(parse_yaml(" recycle-me: &anchor-name a: b c: d recycled: - *anchor-name - *anchor-name ")) #> List of 2 #> $ recycle-me:List of 2 #> ..$ a: chr "b" #> ..$ c: chr "d" #> $ recycled :List of 2 #> ..$ :List of 2 #> .. ..$ a: chr "b" #> .. ..$ c: chr "d" #> ..$ :List of 2 #> .. ..$ a: chr "b" #> .. ..$ c: chr "d" ``` -------------------------------- ### Parse YAML string with a simple mapping Source: https://posit-dev.github.io/r-yaml12/reference/parse_yaml Parses a YAML string containing a mapping and displays the R representation. Uses `dput` to show the structure. ```r dput(parse_yaml("foo: [1, 2, 3]")) #> list(foo = 1:3) ``` -------------------------------- ### Plot write performance Source: https://posit-dev.github.io/r-yaml12/articles/benchmarks Visualizes the write performance benchmark results using `ggplot2`. It plots median run time against object size on a logarithmic scale, with separate lines for each expression. Includes labels for axes and title. ```r write_results_df | ggplot(aes(x = obj_size, y = median, color = expression)) + labs( y = "Median Run Time", x = "Object Size", title = "Write Performance" ) + geom_point() + geom_smooth(linewidth = .5) + scale_x_log10(labels = scales::label_bytes()) + scale_y_continuous(trans = bench::bench_time_trans()) #> `geom_smooth()` using method = 'loess' and formula = 'y ~ x' ``` -------------------------------- ### Handling Tagged Mapping Keys with Custom Handlers Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Applies custom handlers to process tagged mapping keys (`!upper`, `!airport`) during YAML parsing, converting them into R-friendly names. ```r handlers <- list( "!upper" = toupper, "!airport" = function(x) paste0("IATA:", toupper(x)) ) yaml_tagged_key <- " !upper newyork: !airport jfk !upper warsaw: !airport waw " str(parse_yaml(yaml_tagged_key, handlers = handlers)) #> List of 2 #> $ NEWYORK: chr "IATA:JFK" #> $ WARSAW : chr "IATA:WAW" ``` -------------------------------- ### Benchmark YAML Read Performance Source: https://posit-dev.github.io/r-yaml12/articles/benchmarks Measures the time taken to read YAML files using both yaml12::read_yaml and yaml::read_yaml. The results are stored in a list, and file size is added to each result entry. check = FALSE is used to disable result validation during benchmarking. ```r read_results <- lapply(docs, function(doc) { result <- bench::mark( yaml12::read_yaml(doc), yaml::read_yaml(doc), check = FALSE ) result$file_size <- file.info(doc)$size result }) ``` -------------------------------- ### Custom Binary Handler Function Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Defines an R function to handle 'tag:yaml.org,2002:binary' tags, decoding Base64 encoded strings into raw vectors. ```r binary_handler <- function(x) { stopifnot(is.character(x), length(x) == 1) jsonlite::base64_dec(gsub("[ ]", "", x)) } ``` -------------------------------- ### Write YAML with Custom Tags Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Attach `yaml_tag` to an R value before calling `format_yaml()` or `write_yaml()` to emit a custom tag. ```r tagged <- structure("1 + x", yaml_tag = "!expr") write_yaml(tagged) #> --- #> !expr 1 + x #> ... ``` -------------------------------- ### Format a list of documents as a YAML stream Source: https://posit-dev.github.io/r-yaml12/reference/format_yaml Encodes an R list as a YAML stream, where each element is a separate YAML document. This is useful for multi-document YAML files. The `multi = TRUE` argument is essential for this functionality. ```r docs <- list("first", "second") cat(format_yaml(docs, multi = TRUE)) #> --- #> first #> --- #> second ``` -------------------------------- ### Parse a simple tagged scalar Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Demonstrates how yaml12 attaches custom tags as a 'yaml_tag' attribute to scalar values. The tag bypasses normal type inference, always returning the scalar as a string. ```r dput(parse_yaml("!some_tag some_value")) ``` -------------------------------- ### Custom Postprocessor for Tagged Mapping Keys Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Provides a custom R function `eval_yaml_expr_nodes` to recursively process YAML nodes, including tagged mapping keys, and conditionally collapse `yaml_keys`. ```r is_bare_string <- \(x) { is.character(key) && length(key) == 1L && is.null(attributes(key)) } eval_yaml_expr_nodes <- function(x) { if (is.list(x)) { x <- lapply(x, eval_yaml_expr_nodes) if (!is.null(keys <- attr(x, "yaml_keys", TRUE))) { keys <- lapply(keys, eval_yaml_expr_nodes) names(x) <- sapply( \(name, key) if (name == "" && is_bare_string(key)) key else name, names(x), keys ) attr(x, "yaml_keys") <- if (all(sapply(keys, is_bare_string))) NULL else keys } } if (identical(attr(x, "yaml_tag", TRUE), "!expr")) { x <- eval(str2lang(x), globalenv()) } x } ``` -------------------------------- ### Summarize Read Performance Data Source: https://posit-dev.github.io/r-yaml12/articles/benchmarks Combines the benchmark results from multiple files into a single data frame. It also converts the expression names to factors for easier plotting. ```r read_results_df <- bind_rows(read_results) | mutate(expression = as.factor(sapply(expression, deparse1))) ``` -------------------------------- ### Parse YAML Front Matter from R Markdown Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features When `multi = FALSE`, parsing stops after the first document, useful for extracting front matter from files mixing YAML and other text. The parser returns only the first YAML document. ```r rmd_lines <- c( "---", "title: Front matter only", "params:", " answer: 42", "---", "# Body that is not YAML" ) parse_yaml(rmd_lines) #> $title #> [1] "Front matter only" #> #> $params #> #> $params$answer #> [1] 42 ``` -------------------------------- ### Parsing YAML with a Boolean Key Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Demonstrates parsing a YAML mapping where the key is a boolean value. The `yaml_keys` attribute stores the original non-string key. ```yaml true: true ``` -------------------------------- ### Parse tagged expressions using handlers Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Illustrates using a named list of functions as 'handlers' to transform tagged nodes. The '!expr' tag is handled by a function that evaluates the R expression. ```r handlers <- list( "!expr" = function(x) eval(str2lang(x), globalenv()) ) parse_yaml("!expr 1+1", handlers = handlers) ``` -------------------------------- ### Accessing Non-String Keys in R Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Shows how to access the `yaml_keys` attribute in R after parsing YAML with non-string keys, such as a boolean. ```r dput(parse_yaml("true: true")) #> structure(list(TRUE), names = "", yaml_keys = list(TRUE)) ``` -------------------------------- ### Write an R object with a custom YAML tag to stdout Source: https://posit-dev.github.io/r-yaml12/reference/format_yaml Writes an R object with a custom YAML tag to standard output. The `yaml_tag` attribute is preserved in the YAML output, and document start/end markers are included. ```r tagged <- structure("1 + 1", yaml_tag = "!expr") write_yaml(tagged) #> --- #> !expr 1 + 1 #> ... ``` -------------------------------- ### format_yaml Source: https://posit-dev.github.io/r-yaml12/reference/format_yaml Formats an R object as a YAML 1.2 character string. It can optionally treat a list of R objects as multiple YAML documents. ```APIDOC ## format_yaml(value, multi = FALSE) ### Description Formats an R object into a YAML 1.2 character string. If `multi` is `TRUE`, it treats the `value` as a list of YAML documents and encodes a stream. ### Arguments * `value`: Any R object composed of lists, atomic vectors, and scalars. * `multi`: When `TRUE`, treat `value` as a list of YAML documents and encode a stream. ### Value Returns a scalar character string containing YAML. ### Examples ```r cat(format_yaml(list(foo = 1, bar = list(TRUE, NA)))) #> foo: 1 #> bar: #> - true #> - ~ docs <- list("first", "second") cat(format_yaml(docs, multi = TRUE)) #> --- #> first #> --- #> second tagged <- structure("1 + 1", yaml_tag = "!expr") cat(tagged_yaml <- format_yaml(tagged), "\n") #> !expr 1 + 1 dput(parse_yaml(tagged_yaml)) #> structure("1 + 1", yaml_tag = "!expr") ``` ``` -------------------------------- ### read_yaml Source: https://posit-dev.github.io/r-yaml12/reference/parse_yaml Reads YAML content from a file path and parses it into R objects. Similar to `parse_yaml`, it supports handling multiple documents and controlling sequence simplification. ```APIDOC ## read_yaml ### Description Reads YAML content from a file path and parses it into R objects. Similar to `parse_yaml`, it supports handling multiple documents and controlling sequence simplification. ### Arguments - **path** (character string) - Scalar string path to a YAML file. - **multi** (logical) - When `TRUE`, return a list containing all documents in the stream. - **simplify** (logical) - When `FALSE`, keep YAML sequences as R lists instead of simplifying to atomic vectors. - **handlers** (named list) - Named list of R functions with names corresponding to YAML tags; matching handlers transform tagged values. ### Value When `multi = FALSE`, returns a parsed R object for the first document. When `multi = TRUE`, returns a list of parsed documents. ### Details YAML tags without a corresponding `handler` are preserved in a `yaml_tag` attribute. Mappings with keys that are not all simple scalar strings are returned as a named list with a `yaml_keys` attribute. ### Examples ```r # Read from a file; keep sequences as lists. path <- tempfile(fileext = ".yaml") writeLines("alpha: [true, null]\nbeta: 3.5", path) str(read_yaml(path, simplify = FALSE)) #> List of 2 #> $ alpha:List of 2 #> ..$ : logi TRUE #> ..$ : NULL #> $ beta : num 3.5 ``` ``` -------------------------------- ### Post-processing tagged nodes manually Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Provides a custom function to recursively walk parsed YAML structures and evaluate '!expr' tagged scalars. This offers more control than using handlers during parsing. ```r eval_yaml_expr_nodes <- function(x) { if (is.list(x)) { x <- lapply(x, eval_yaml_expr_nodes) } else if (identical(attr(x, "yaml_tag", TRUE), "!expr")) { x <- eval(str2lang(x), globalenv()) } x } safe_loaded <- parse_yaml("!expr 1 + 1") dput(safe_loaded) eval_yaml_expr_nodes(safe_loaded) ``` -------------------------------- ### Tagged boolean scalar parsing Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Shows that a tagged scalar like '! true' is parsed as a string, unlike an untagged 'true' which is parsed as a logical TRUE. The tag is preserved as a 'yaml_tag' attribute. ```r parse_yaml("! true") ``` ```r parse_yaml("true") ``` -------------------------------- ### Handler error during parsing Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Demonstrates that errors occurring within a handler function will stop the parsing process. ```r parse_yaml("!expr stop('boom')", handlers = handlers) ``` -------------------------------- ### parse_yaml Source: https://posit-dev.github.io/r-yaml12/reference/parse_yaml Parses a character vector containing YAML content into R objects. It can handle single or multiple YAML documents and offers control over sequence simplification. ```APIDOC ## parse_yaml ### Description Parses a character vector containing YAML content into R objects. It can handle single or multiple YAML documents and offers control over sequence simplification. ### Arguments - **text** (character vector) - Elements are concatenated with `"\n"`. - **multi** (logical) - When `TRUE`, return a list containing all documents in the stream. - **simplify** (logical) - When `FALSE`, keep YAML sequences as R lists instead of simplifying to atomic vectors. - **handlers** (named list) - Named list of R functions with names corresponding to YAML tags; matching handlers transform tagged values. ### Value When `multi = FALSE`, returns a parsed R object for the first document. When `multi = TRUE`, returns a list of parsed documents. ### Details YAML tags without a corresponding `handler` are preserved in a `yaml_tag` attribute. Mappings with keys that are not all simple scalar strings are returned as a named list with a `yaml_keys` attribute. ### Examples ```r dput(parse_yaml("foo: [1, 2, 3]")) #> list(foo = 1:3) # homogeneous sequences simplify by default. # YAML null maps to NA in otherwise homogeneous sequences. dput(parse_yaml("foo: [1, 2, 3, null]")) #> list(foo = c(1L, 2L, 3L, NA)) # mixed type sequence never simplify dput(parse_yaml("[1, true, cat]")) #> list(1L, TRUE, "cat") # use `simplify=FALSE` to always return sequences as lists. str(parse_yaml("foo: [1, 2, 3, null]", simplify = FALSE)) #> List of 1 #> $ foo:List of 4 #> ..$ : int 1 #> ..$ : int 2 #> ..$ : int 3 #> ..$ : NULL # Parse multiple documents when requested. stream <- " --- first: 1 --- second: 2 " str(parse_yaml(stream, multi = TRUE)) #> List of 2 #> $ :List of 1 #> ..$ first: int 1 #> $ :List of 1 #> ..$ second: int 2 ``` ``` -------------------------------- ### Custom Timestamp Handler Function Source: https://posit-dev.github.io/r-yaml12/articles/yaml-tags-and-advanced-features Defines an R function to handle 'tag:yaml.org,2002:timestamp' tags, converting date-only strings to Date objects and others to POSIXct. ```r timestamp_handler <- function(x) { stopifnot(is.character(x), length(x) == 1) if (grepl("^\\d{4}-\\d{2}-\\d{2}$", x)) { return(as.Date(x)) } formats <- c( "%Y-%m-%dT%H:%M:%OS%z", "%Y-%m-%d %H:%M:%OS%z", "%Y-%m-%dT%H:%M:%OS", "%Y-%m-%d %H:%M:%OS", "%Y-%m-%d %H:%M" ) as.POSIXct(x, tryFormats = formats, optional = TRUE) } ``` -------------------------------- ### YAML Folded Block Scalar Source: https://posit-dev.github.io/r-yaml12/articles/yaml-2-minute-intro Parses a folded block scalar, joining lines with spaces. ```yaml > hello world ``` -------------------------------- ### Define Mixed Node for YAML Source: https://posit-dev.github.io/r-yaml12/articles/benchmarks Defines a complex R list structure representing a YAML node. This node includes various data types (string, block string, booleans, integers, floats, null) to exercise the YAML 1.2 core schema. ```r # A YAML node that exercises every core schema type: # seq, map, str, bool, int, float, null mixed_node <- list( str = c( "Lorem ipsum dolor sit amet, vel accumsan vitae faucibus ultrices leo", "neque? Et cursus lacinia, ut, sit donec facilisi eu interdum. Dui", "ipsum, vitae ligula commodo convallis ac sed nunc. Ipsum at nec lacus", "eros suscipit vitae." ), block_str = "lorem \n ipsum \n dolor\n", bools = c(TRUE, FALSE), ints = c(123L, -123L), floats = c(123.456, -123.456), null = NULL ) ``` -------------------------------- ### YAML Literal Block Scalar Source: https://posit-dev.github.io/r-yaml12/articles/yaml-2-minute-intro Parses a literal block scalar, preserving newlines. ```yaml | hello world ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.