Movatterモバイル変換


[0]ホーム

URL:


Type:Package
Title:Methods to Convert R Data to YAML and Back
Version:2.3.12
Description:Implements the 'libyaml' 'YAML' 1.1 parser and emitter (https://pyyaml.org/wiki/LibYAML) for R.
License:BSD_3_clause + file LICENSE
URL:https://yaml.r-lib.org,https://github.com/r-lib/yaml/
BugReports:https://github.com/r-lib/yaml/issues
Suggests:knitr, rmarkdown, testthat (≥ 3.0.0)
Config/testthat/edition:3
Config/Needs/website:tidyverse/tidytemplate
Encoding:UTF-8
RoxygenNote:7.3.3
VignetteBuilder:knitr
NeedsCompilation:yes
Packaged:2025-12-08 16:53:07 UTC; hadleywickham
Author:Hadley WickhamORCID iD [cre], Shawn GarbettORCID iD [ctb], Jeremy Stephens [aut, ctb], Kirill Simonov [aut], Yihui XieORCID iD [ctb], Zhuoer Dong [ctb], Jeffrey Horner [ctb], reikoch [ctb], Will BeasleyORCID iD [ctb], Brendan O'Connor [ctb], Michael Quinn [ctb], Charlie Gao [ctb], Gregory R. Warnes [ctb], Zhian N. Kamvar [ctb]
Maintainer:Hadley Wickham <hadley@posit.co>
Repository:CRAN
Date/Publication:2025-12-10 07:00:01 UTC

yaml: Methods to Convert R Data to YAML and Back

Description

Implements the 'libyaml' 'YAML' 1.1 parser and emitter (https://pyyaml.org/wiki/LibYAML) for R.

Author(s)

Maintainer: Hadley Wickhamhadley@posit.co (ORCID)

Authors:

Other contributors:

See Also

Useful links:


Convert an R object into a YAML string

Description

If you set theomap option to TRUE, as.yaml will create ordered maps(or omaps) instead of normal maps.

Usage

as.yaml(  x,  line.sep = c("\n", "\r\n", "\r"),  indent = 2,  omap = FALSE,  column.major = TRUE,  unicode = TRUE,  precision = getOption("digits"),  indent.mapping.sequence = FALSE,  handlers = NULL)

Arguments

x

The object to be converted.

line.sep

The line separator character(s) to use.

indent

The number of spaces to use for indenting.

omap

Determines whether or not to convert a list to a YAML omap; seeDetails.

column.major

Determines how to convert a data.frame; see Details.

unicode

Determines whether or not to allow unescaped unicodecharacters in output.

precision

Number of significant digits to use when formatting numericvalues.

indent.mapping.sequence

Determines whether or not to indent sequencesin mapping context.

handlers

Named list of custom handler functions for R objects; seeDetails.

Details

Thecolumn.major option determines how a data frame is converted. IfTRUE, the data frame is converted into a map of sequences where the name ofeach column is a key. If FALSE, the data frame is converted into a sequenceof maps, where each element in the sequence is a row. You'll probablyalmost always want to leave this as TRUE (which is the default), becauseusingyaml.load() on the resulting string returns an objectwhich is much more easily converted into a data frame viaas.data.frame().

You can specify custom handler functions via thehandlers argument.This argument must be a named list of functions, where the names are Robject class names (i.e., 'numeric', 'data.frame', 'list', etc). Thefunction(s) you provide will be passed one argument (the R object) and canreturn any R object. The returned object will be emitted normally.

Character vectors that have a class of ‘verbatim’ will not be quotedin the output YAML document except when the YAML specification requires it.This means that you cannot do anything that would result in an invalid YAMLdocument, but you can emit strings that would otherwise be quoted. This isuseful for changing how logical vectors are emitted (see below for example).

Character vectors that have an attribute of ‘quoted’ will be wrappedin double quotes (see below for example).

You can specify YAML tags for R objects by setting the ‘tag’attribute to a character vector of length 1. If you set a tag for a vector,the tag will be applied to the YAML sequence as a whole, unless the vectorhas only 1 element. If you wish to tag individual elements, you must use alist of 1-length vectors, each with a tag attribute. Likewise, if you set atag for an object that would be emitted as a YAML mapping (like a data frameor a named list), it will be applied to the mapping as a whole. Tags can beused in conjunction with YAML deserialization functions likeyaml.load() via custom handlers, however, if you set an internaltag on an incompatible data type (like “!seq 1.0”), errors will occurwhen you try to deserialize the document.

Value

Returns a YAML string which can be loaded usingyaml.load() or copied into a file for external use.

Author(s)

Jeremy Stephensjeremy.f.stephens@vumc.org

References

YAML: http://yaml.org

YAML omap type: http://yaml.org/type/omap.html

See Also

yaml.load()

Examples

  as.yaml(1:10)  as.yaml(list(foo=1:10, bar=c("test1", "test2")))  as.yaml(list(foo=1:10, bar=c("test1", "test2")), indent=3)  as.yaml(list(foo=1:10, bar=c("test1", "test2")), indent.mapping.sequence=TRUE)  as.yaml(data.frame(a=1:10, b=letters[1:10], c=11:20))  as.yaml(list(a=1:2, b=3:4), omap=TRUE)  as.yaml("multi\nline\nstring")  as.yaml(function(x) x + 1)  as.yaml(list(foo=list(list(x = 1, y = 2), list(x = 3, y = 4))))  # custom handler  as.yaml(Sys.time(), handlers = list(    POSIXct = function(x) format(x, "%Y-%m-%d")  ))  # custom handler with verbatim output to change how logical vectors are  # emitted  as.yaml(c(TRUE, FALSE), handlers = list(    logical = verbatim_logical))  # force quotes around a string  port_def <- "80:80"  attr(port_def, "quoted") <- TRUE  x <- list(ports = list(port_def))  as.yaml(x)  # custom tag for scalar  x <- "thing"  attr(x, "tag") <- "!thing"  as.yaml(x)  # custom tag for sequence  x <- 1:10  attr(x, "tag") <- "!thing"  as.yaml(x)  # custom tag for mapping  x <- data.frame(a = letters[1:5], b = letters[6:10])  attr(x, "tag") <- "!thing"  as.yaml(x)  # custom tag for each element in a list  x <- list(1, 2, 3)  attr(x[[1]], "tag") <- "!a"  attr(x[[2]], "tag") <- "!b"  attr(x[[3]], "tag") <- "!c"  as.yaml(x)

Read a YAML file

Description

Read a YAML document from a file and create an R object from it

Usage

read_yaml(  file,  fileEncoding = "UTF-8",  text,  error.label,  readLines.warn = TRUE,  ...)

Arguments

file

Either a character string naming a file or aconnectionopen for reading.

fileEncoding

Character string: if non-empty declares the encodingused on a file (not a connection) so the character data can be re-encoded.Seefile().

text

Character string: iffile is not supplied and this is,then data are read from the value oftext via a text connection.Notice that a literal string can be used to include (small) data setswithin R code.

error.label

A label to prepend to error messages (see Details).

readLines.warn

Logical (default: TRUE). Suppress warnings fromreadLines used inside read_yaml.

...

Arguments to pass toyaml.load().

Details

This function is a convenient wrapper foryaml.load() and is anicer alternative toyaml.load_file().

You can specify a label to be prepended to error messages via theerror.label argument. Iferror.label is missing,read_yaml will make an educated guess for the value oferror.label by either using the specified filename (whenfileis a character vector) or using the description of the supplied connectionobject (via thesummary function). Iftext is used, thedefault value oferror.label will beNULL.

Value

If the root YAML object is a map, a named list or list with anattribute of 'keys' is returned. If the root object is a sequence, a listor vector is returned, depending on the contents of the sequence. A vectorof length 1 is returned for single objects.

Author(s)

Jeremy Stephensjeremy.f.stephens@vumc.org

References

YAML: http://yaml.org

libyaml: https://pyyaml.org/wiki/LibYAML

See Also

yaml.load(),write_yaml(),yaml.load_file()

Examples

## Not run:   # reading from a file connection  filename <- tempfile()  cat("test: data\n", file = filename)  con <- file(filename, "r")  read_yaml(con)  close(con)  # using a filename to specify input file  read_yaml(filename)## End(Not run)  # reading from a character vector  read_yaml(text="- hey\n- hi\n- hello")

Alternative logical handler

Description

A yaml handler function that causes logical vectors to emittrue/false instead ofyes/no values.

Usage

verbatim_logical(x)

Arguments

x

Logical vector to convert totrue/false.

Details

Pass this function toas.yaml() as part of thehandlers argument list likelist(logical = verbatim_logical).

Value

Returns a vector of strings of eithertrue orfalse ofclassverbatim.

Author(s)

Charles Dupont and James Goldie (jimjam-slam)

See Also

as.yaml()

Examples

vector <- c(TRUE, FALSE, TRUE)as.yaml(vector, handlers=list(logical=verbatim_logical))

Write a YAML file

Description

Write the YAML representation of an R object to a file

Usage

write_yaml(x, file, fileEncoding = "UTF-8", ...)

Arguments

x

The object to be converted.

file

Either a character string naming a file or aconnectionopen for writing.

fileEncoding

Character string: if non-empty declares the encoding tobe used on a file (not a connection) so the character data can bere-encoded as they are written. Seefile().

...

Arguments toas.yaml().

Details

Iffile is a non-open connection, an attempt is made to open it andthen close it after use.

This function is a convenient wrapper aroundas.yaml().

Author(s)

Jeremy Stephensjeremy.f.stephens@vumc.org

See Also

as.yaml(),read_yaml(),yaml.load_file()

Examples

## Not run:   # writing to a file connection  filename <- tempfile()  con <- file(filename, "w")  write_yaml(data.frame(a=1:10, b=letters[1:10], c=11:20), con)  close(con)  # using a filename to specify output file  write_yaml(data.frame(a=1:10, b=letters[1:10], c=11:20), filename)## End(Not run)

Convert a YAML string into R objects

Description

Parse a YAML string and return R objects.

Usage

yaml.load(  string,  as.named.list = TRUE,  handlers = NULL,  error.label = NULL,  eval.expr = getOption("yaml.eval.expr", FALSE),  merge.precedence = c("order", "override"),  merge.warning = FALSE)yaml.load_file(input, error.label, readLines.warn = TRUE, ...)

Arguments

string

The YAML string to be parsed.

as.named.list

Whether or not to return a named list for maps (TRUE bydefault).

handlers

Named list of custom handler functions for YAML types (seeDetails).

error.label

A label to prepend to error messages (see Details).

eval.expr

Whether or not to evaluate expressions found in the YAMLdocument (see Details).

merge.precedence

Precedence behavior during map merges (seeDetails).

merge.warning

Whether or not to warn about ignored key/value pairsduring map merges.

input

A filename or connection; ifinput is a filename, thatfile must be encoded in UTF-8.

readLines.warn

Logical (default: TRUE). Suppress warnings fromreadLines used inside read_yaml.

...

Arguments to pass to yaml.load.

Details

Useyaml.load to load a YAML string. For files and connections, useyaml.load_file, which callsyaml.load with the contents of thespecified file or connection.

Sequences of uniform data (e.g. a sequence of integers) are converted intovectors. If the sequence is not uniform, it's returned as a list. Maps areconverted into named lists by default, and all the keys in the map areconverted to strings. If you don't want the keys to be coerced intostrings, setas.named.list to FALSE. When it's FALSE, a list will bereturned with an additional attribute named 'keys', which is a list of theun-coerced keys in the map (in the same order as the main list).

You can specify custom handler functions via thehandlers argument.This argument must be a named list of functions, where the names are theYAML types (i.e., 'int', 'float', 'seq', etc). The functions you providewill be passed one argument. Custom handler functions for string types (alltypes except sequence and map) will receive a character vector of length 1.Custom sequence functions will be passed a list of objects. Custom mapfunctions will be passed the object that the internal map handler creates,which is either a named list or a list with a 'keys' attribute (depending onas.named.list). ALL functions you provide must return an object.See the examples for custom handler use.

You can specify a label to be prepended to error messages via theerror.label argument. When usingyaml.load_file, you caneither set theerror.label argument explicitly or leave it missing.If missing,yaml.load_file will make an educated guess for the valueoferror.label by either using the specified filename (wheninput is a character vector) or using the description of the suppliedconnection object (via thesummary function). You can explicitly seterror.label toNULL if you don't want to use thisfunctionality.

There is a built-in handler that will evaluate expressions that are taggedwith the ‘!expr’ tag. Currently this handler is disabled by defaultfor security reasons. If a ‘!expr’ tag exists and this is set toFALSE a warning will occur. Alternately, you can set the option named‘yaml.eval.expr’ via theoptions function to turn onevaluation.

Themerge.precedence parameter controls how merge keys are handled.The YAML merge key specification is not specific about how key/valueconflicts are resolved during map merges. As a result, various YAML libraryimplementations vary in merge key behavior (notably Python and Ruby). Thispackage's default behavior (whenmerge.precedence is ‘order’)is to give precedence to key/value pairs that appear first. If you setmerge.precedence to ‘override’, natural map key/value pairswill override any duplicate keys found in merged maps, regardless of order.This is the default behavior in Python's YAML library.

This function uses the YAML parser provided by libyaml, which conforms tothe YAML 1.1 specification.

Value

If the root YAML object is a map, a named list or list with anattribute of 'keys' is returned. If the root object is a sequence, a listor vector is returned, depending on the contents of the sequence. A vectorof length 1 is returned for single objects.

Author(s)

Jeremy Stephensjeremy.f.stephens@vumc.org

References

YAML: http://yaml.org

libyaml: https://pyyaml.org/wiki/LibYAML

YAML merge specification: http://yaml.org/type/merge.html

See Also

as.yaml()

Examples

  yaml.load("- hey\n- hi\n- hello")  yaml.load("foo: 123\nbar: 456")  yaml.load("- foo\n- bar\n- 3.14")  yaml.load("foo: bar\n123: 456", as.named.list = FALSE)## Not run:   # reading from a file (uses readLines internally)  filename <- tempfile()  cat("foo: 123", file=filename, sep="\n")  yaml.load_file(filename)## End(Not run)  # custom scalar handler  my.float.handler <- function(x) { as.numeric(x) + 123 }  yaml.load("123.456", handlers=list("float#fix"=my.float.handler))  # custom sequence handler  yaml.load("- 1\n- 2\n- 3", handlers=list(seq=function(x) { as.integer(x) + 3 }))  # custom map handler  yaml.load("foo: 123", handlers=list(map=function(x) { x$foo <- x$foo + 123; x }))  # handling custom types  yaml.load("!sqrt 555", handlers=list(sqrt=function(x) { sqrt(as.integer(x)) }))  yaml.load("!foo\n- 1\n- 2", handlers=list(foo=function(x) { as.integer(x) + 1 }))  yaml.load("!bar\none: 1\ntwo: 2", handlers=list(bar=function(x) { x$one <- "one"; x }))  # loading R expressions  # NOTE: this will not be done by default in the near future  doc <- yaml.load("inc: !expr function(x) x + 1", eval.expr=TRUE)  doc$inc(1)  # adding a label to error messages  try(yaml.load("*", error.label = "foo"))

[8]ページ先頭

©2009-2025 Movatter.jp