Examples for 'yaml::as.yaml'


Convert an R object into a YAML string

Aliases: as.yaml

Keywords: data manip

### ** Examples

  as.yaml(1:10)
[1] "- 1\n- 2\n- 3\n- 4\n- 5\n- 6\n- 7\n- 8\n- 9\n- 10\n"
  as.yaml(list(foo=1:10, bar=c("test1", "test2")))
[1] "foo:\n- 1\n- 2\n- 3\n- 4\n- 5\n- 6\n- 7\n- 8\n- 9\n- 10\nbar:\n- test1\n- test2\n"
  as.yaml(list(foo=1:10, bar=c("test1", "test2")), indent=3)
[1] "foo:\n- 1\n- 2\n- 3\n- 4\n- 5\n- 6\n- 7\n- 8\n- 9\n- 10\nbar:\n- test1\n- test2\n"
  as.yaml(list(foo=1:10, bar=c("test1", "test2")), indent.mapping.sequence=TRUE)
[1] "foo:\n  - 1\n  - 2\n  - 3\n  - 4\n  - 5\n  - 6\n  - 7\n  - 8\n  - 9\n  - 10\nbar:\n  - test1\n  - test2\n"
  as.yaml(data.frame(a=1:10, b=letters[1:10], c=11:20))
[1] "a:\n- 1\n- 2\n- 3\n- 4\n- 5\n- 6\n- 7\n- 8\n- 9\n- 10\nb:\n- a\n- b\n- c\n- d\n- e\n- f\n- g\n- h\n- i\n- j\nc:\n- 11\n- 12\n- 13\n- 14\n- 15\n- 16\n- 17\n- 18\n- 19\n- 20\n"
  as.yaml(list(a=1:2, b=3:4), omap=TRUE)
[1] "!!omap\n- a:\n  - 1\n  - 2\n- b:\n  - 3\n  - 4\n"
  as.yaml("multi\nline\nstring")
[1] "|-\n  multi\n  line\n  string\n"
  as.yaml(function(x) x + 1)
[1] "!expr |\n  function (x)\n  x + 1\n"
  as.yaml(list(foo=list(list(x = 1, y = 2), list(x = 3, y = 4))))
[1] "foo:\n- x: 1.0\n  'y': 2.0\n- x: 3.0\n  'y': 4.0\n"
  # custom handler
  as.yaml(Sys.time(), handlers = list(
    POSIXct = function(x) format(x, "%Y-%m-%d")
  ))
[1] "'2025-08-11'\n"
  # custom handler with verbatim output to change how logical vectors are
  # emitted
  as.yaml(c(TRUE, FALSE), handlers = list(
    logical = verbatim_logical))
[1] "- true\n- false\n"
  # force quotes around a string
  port_def <- "80:80"
  attr(port_def, "quoted") <- TRUE
  x <- list(ports = list(port_def))
  as.yaml(x)
[1] "ports:\n- \"80:80\"\n"
  # custom tag for scalar
  x <- "thing"
  attr(x, "tag") <- "!thing"
  as.yaml(x)
[1] "!thing thing\n"
  # custom tag for sequence
  x <- 1:10
  attr(x, "tag") <- "!thing"
  as.yaml(x)
[1] "!thing\n- 1\n- 2\n- 3\n- 4\n- 5\n- 6\n- 7\n- 8\n- 9\n- 10\n"
  # custom tag for mapping
  x <- data.frame(a = letters[1:5], b = letters[6:10])
  attr(x, "tag") <- "!thing"
  as.yaml(x)
[1] "!thing\na:\n- a\n- b\n- c\n- d\n- e\nb:\n- f\n- g\n- h\n- i\n- j\n"
  # 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)
[1] "- !a 1.0\n- !b 2.0\n- !c 3.0\n"

[Package yaml version 2.3.10 Index]