Atomic: Atomic: a class for strict atomic vectors

Description Usage Arguments Value Self-validation Updating fields of the Atomic class Super class Public fields Methods Author(s) See Also Examples

Description

Atomic is an important building block of blueprint: it creates blueprints for strict atomic vectors (vectors of any R atomic type, including NULL, that has no attribute). Instances of the Atomic class hold useful (derived) metadata on strict vectors: their types, names, prototypes and optionally, their lengths.

Usage

1
2
3
4
5
## Test if an object is an 'Atomic' object
is_atomic(x)

## Validate if an object is a proper 'Atomic' object
valid_atomic(x)

Arguments

x

any R object.

Value

Self-validation

The contents of an instance is checked when it is initialized and each time a method is called afterward.

Updating fields of the Atomic class

Users should never manually change fields' values of an Atomic instance manually. Instead, use $set() to do it safely. Refer to the documentation of this method (see below) for more information.

Super class

blueprint::Blueprint -> Atomic

Public fields

name

A non-empty, non-NA scalar character. A name for the vector.

type

A non-empty, non-NA scalar character. The class of the vector.

length

A scalar integer. The length of the vector. If NULL, it is ignored by the class instance.

Methods

Public methods

Inherited methods

Method new()

Create an Atomic object.

Usage
Atomic$new(atomic, name = character(), length = NULL)
Arguments
atomic

any strict atomic R vector.

name

A non-empty, non-NA scalar character. The name of the vector passed to atomic.

length

A scalar integer. This argument is flexible. If NULL, $length is ignored.

Returns

A R6 object of class Atomic.

Examples
## Create a blueprint and do not enforce a length.
Atomic$new(1L, "myVectorName")

## Create a blueprint that enforces a specific length; here, 10.
Atomic$new(1L, "myVectorName", 10L)

Method validate()

Validate an Atomic object.

Usage
Atomic$validate()
Returns

The Atomic object invisibly if the object is valid. Else, an error explaining what is wrong with the object.


Method print()

Print an Atomic object.

Usage
Atomic$print()
Details

The object is automatically validated before being printed.

Returns

The Atomic object invisibly.


Method format()

Format an Atomic object.

Usage
Atomic$format(.validate = TRUE)
Arguments
.validate

A scalar logical. Validate the object before calling the method? While this argument is available to the users, it should be ignored, unless you have an alternative way to make sure your underlying object is valid. Since it is a low-level argument, it is not validated, so proceed with care.

Returns

A character scalar representing the formatted Atomic object.


Method compare()

Compare an object against an Atomic.

Usage
Atomic$compare(object, .validate = TRUE)
Arguments
object

Any R object.

.validate

A scalar logical. Validate the object before calling the method? While this argument is available to the users, it should be ignored, unless you have an alternative way to make sure your underlying object is valid. Since it is a low-level argument, it is not validated, so proceed with care.

Returns

A scalar logical. A TRUE means that object is in compliance with the underlying Atomic:

  1. it has the same $type and

  2. if $length is not NULL, it has the same prescribed length.

Examples
## Compare values against an Atomic blueprint that do not enforce a length.
bp_no_length <- Atomic$new("hello", "myBlueprint")

bp_no_length$compare(c("hi", "bye")) # TRUE
bp_no_length$compare("bye")          # TRUE
bp_no_length$compare(1)              # FALSE

## Compare values against an Atomic blueprint that enforces a length.
bp_length <- Atomic$new("hello", "myBlueprint", 1L)

bp_length$compare(c("hi", "bye")) # FALSE
bp_length$compare("bye")          # TRUE
bp_length$compare(1)              # FALSE

Method generate()

Create (spawn) a strict atomic vector from an Atomic object.

Usage
Atomic$generate(.validate = TRUE)
Arguments
.validate

A scalar logical. Validate the object before calling the method? While this argument is available to the users, it should be ignored, unless you have an alternative way to make sure your underlying object is valid. Since it is a low-level argument, it is not validated, so proceed with care.

Returns

A strict atomic vector. Its underlying type and length is respectively given by fields $type and $length. It is initialized with a suitable prototype derived from argument atomic (see $new()) and registered internally when the object is created.


Method bind()

Create a strict atomic vector from an Atomic object and bind it to $name in a given environment or list-like object.

This is an experimental feature.

Usage
Atomic$bind(where = parent.frame(), lock = FALSE, .validate = TRUE)
Arguments
where

An environment or a list-like object.

lock

A scalar logical. If where is an environment, should the binding be locked? If so, it cannot be changed until it is unlocked.

.validate

A scalar logical. Validate the object before calling the method? While this argument is available to the users, it should be ignored, unless you have an alternative way to make sure your underlying object is valid. Since it is a low-level argument, it is not validated, so proceed with care.

Returns

The Atomic object invisibly if the object is valid. Else, an error explaining what is wrong with the object.

Examples
## Create an environment.
env <- new.env()

## Spawn a vector from a blueprint and bind the result to $name
## in env. We also lock the binding.
b <- Atomic$new(12.0, "vector", 1000L)$bind(env, TRUE)

## Trying to change value of a locked binding results in an error.
\dontrun{env$vector <- 1.0}

## You can later unlock the binding.
unlockBinding("vector", env)
env$vector <- "new value"

## Bind a prototype to $name within a list.
lst <- list(value = 1L)
b$bind(lst)
lst$vector

Method as_list()

Coerce an Atomic object to a list.

Usage
Atomic$as_list(.validate = TRUE)
Arguments
.validate

A scalar logical. Validate the object before calling the method? While this argument is available to the users, it should be ignored, unless you have an alternative way to make sure your underlying object is valid. Since it is a low-level argument, it is not validated, so proceed with care.

Returns

A named list of four elements:

name A scalar character equal to $name.
type A scalar character equal to $type.
length A scalar integer equal to $length or NULL.
prototype A scalar strict atomic value with a class and a type attribute equal to $type.

Method as_character()

Coerce an Atomic object to a character.

Usage
Atomic$as_character(.validate = TRUE)
Arguments
.validate

A scalar logical. Validate the object before calling the method? While this argument is available to the users, it should be ignored, unless you have an alternative way to make sure your underlying object is valid. Since it is a low-level argument, it is not validated, so proceed with care.

Returns

A named character of three elements:

name A scalar character equal to $name.
type A scalar character equal to $type.
length A scalar character equal to the coerced value of $length (from integer to character). If $length is NULL, the string "NULL" is returned.

Method as_yaml()

Convert an Atomic object to a YAML text based format.

Usage
Atomic$as_yaml(
  file = character(),
  headers = list(),
  handlers = list(),
  source_header = TRUE,
  ...,
  .validate = TRUE
)
Arguments
file

A scalar character. The name of a file to be created. If missing, a string will be returned to the console.

headers

A non-empty named list that holds additional key/value pairs to include in text representations of the object (either JSON or YAML). Ignore this argument if not needed.

handlers

A named list of custom functions passed to yaml::as.yaml(). These handle how objects should be converted into a YAML string. For more information, see argument handlers of yaml::as.yaml(). If missing, a default list of handlers is used. Users can overwrite them, but be advised that this should be reserved to expert users.

source_header

A scalar logical. Should a 'source' header be added? This header gives information on how the text representation was generated.

...

further arguments passed to yaml::as.yaml(). You cannot pass argument handlers.

.validate

A scalar logical. Validate the object before calling the method? While this argument is available to the users, it should be ignored, unless you have an alternative way to make sure your underlying object is valid. Since it is a low-level argument, it is not validated, so proceed with care.

Details

YAML (YAML Ain't Markup Language, a recursive name) is a human-friendly data serialization standard usable in almost any programming language. It is designed to be a strict super-set of JSON (see as_json()). To learn more, visit yaml.org.

Method as_yaml() automatically re-encodes its fields to UTF-8 (if applicable) before returning or writing the YAML output. Additional headers passed to headers are also re-encoded, if applicable.

By default, raw values will be encoded into a base64 string. This string can be decoded again into raw values by using function jsonlite::base64_dec(). Users can overwrite this default behavior by passing a custom raw handler function to argument handlers.

Returns

If file is missing, a scalar character holding a YAML string derived from method as_list(). Else, the output is written to file and the Atomic object is returned invisibly.

Examples
## Create an Atomic object.
ab <- Atomic$new(sample.int(10L), "randomValues", 10L)

## Create a simple YAML representation and print it.
cat(ab$as_yaml())

## Add additional headers to output.
myheaders <- list(author = "JM Potvin", date = "January 1st 2021")
cat(ab$as_yaml(headers = myheaders))

## Write output to a file.
path <- tempfile(fileext = ".yaml")
ab$as_yaml(file = path, headers = myheaders)

## Output is always encoded to UTF-8.
Encoding(ab$as_yaml(headers = list(utf8char = "`"))) == "UTF-8"

## You can pass additional parameters to yaml::as.yaml().
cat(ab$as_yaml(indent = 4L))

## Use custom handlers.
## Here, we use another handler for raw values.
handlers <- list(
    raw = function(x) { return(as.character(x)) }
)
ab$as_yaml(handlers = handlers)

Method as_json()

Convert an Atomic object to a JSON text based format.

Usage
Atomic$as_json(
  file = character(),
  headers = list(),
  source_header = TRUE,
  ...,
  .validate = TRUE
)
Arguments
file

A scalar character. The name of a file to be created. If missing, a string will be returned to the console.

headers

A non-empty named list that holds additional key/value pairs to include in text representations of the object (either JSON or YAML). Ignore this argument if not needed.

source_header

A scalar logical. Should a 'source' header be added? This header gives information on how the text representation was generated.

...

further arguments passed to jsonlite::toJSON(). You cannot passe arguments x and path.

.validate

A scalar logical. Validate the object before calling the method? While this argument is available to the users, it should be ignored, unless you have an alternative way to make sure your underlying object is valid. Since it is a low-level argument, it is not validated, so proceed with care.

Details

JSON (JavaScript Object Notation) is a lightweight and human-friendly data serialization format usable in almost any programming language. Its design is derived from JavaScript's objects notation. Compared to YAML, it is slightly more verbose. To learn more, visit www.json.org.

Method as_json() automatically re-encodes its fields to UTF-8 (if applicable) before returning or writing the JSON output. Additional headers passed to headers are also re-encoded, if applicable.

By default, raw values will be encoded into a base64 string. This string can be decoded again into raw values by using function jsonlite::base64_dec(). Users can overwrite this default behavior. See argument raw of jsonlite::toJSON().

Returns

If file is missing, a scalar character holding a JSON string derived from method as_list(). This string is encapsulated into an object of class json, which is internally defined in package jsonlite and behaves like a normal character. Else, the output is written to file and the Atomic object is returned invisibly.

Examples
## Create an Atomic object.
ab <- Atomic$new(sample.int(10L), "randomValues", 10L)

## Create a simple JSON representation and print it.
cat(ab$as_json())

## Add additional headers to output.
myheaders <- list(author = "JM Potvin", date = "January 1st 2021")
cat(ab$as_json(headers = myheaders))

## Write output to a file.
path <- tempfile(fileext = ".json")
ab$as_json(file = path, headers = myheaders)

## Output is always encoded to UTF-8.
Encoding(ab$as_json(headers = list(utf8char = "`"))) == "UTF-8"

## You can pass additional parameters to jsonlite::toJSON().
cat(ab$as_json(headers = list(test = 1.23456789)))
cat(ab$as_json(headers = list(test = 1.23456789), digits = 8L))

Method set()

Update a field's value of an Atomic object.

Usage
Atomic$set(field = character(), value, .validate = TRUE)
Arguments
field

A scalar character. The name of a field.

value

Any R value. The value to use when updating a field. Its type must match the field's underlying structure.

.validate

A scalar logical. Validate the object before calling the method? While this argument is available to the users, it should be ignored, unless you have an alternative way to make sure your underlying object is valid. Since it is a low-level argument, it is not validated, so proceed with care.

Details

Changing the value of field $type is forbidden, because it could break internal prototyping mechanisms. Attempting to do so will result in an error. If $type must be changed, create a new Atomic object instead.

It is worthwhile to note that Atomic$set() is a safe wrapper that calls Blueprint$set().

Returns

The Atomic object invisibly if the object is valid. Else, an error explaining what is wrong with the object.

Examples
## Update $name. You could also update $length.
b <- Atomic$new(double(10L), "wrong-name")
b$set("name", "good-name")$print()

## Trying to update $type will throw an error.
\dontrun{
b$set("type", "raw")
}
b_new <- Atomic$new(raw(10L), "good-name")

Author(s)

Jean-Mathieu Potvin (jm@potvin.xyz)

See Also

Other Blueprint classes: Blueprint

Examples

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
## ------------------------------------------------
## Method `Atomic$new`
## ------------------------------------------------

## Create a blueprint and do not enforce a length.
Atomic$new(1L, "myVectorName")

## Create a blueprint that enforces a specific length; here, 10.
Atomic$new(1L, "myVectorName", 10L)

## ------------------------------------------------
## Method `Atomic$compare`
## ------------------------------------------------

## Compare values against an Atomic blueprint that do not enforce a length.
bp_no_length <- Atomic$new("hello", "myBlueprint")

bp_no_length$compare(c("hi", "bye")) # TRUE
bp_no_length$compare("bye")          # TRUE
bp_no_length$compare(1)              # FALSE

## Compare values against an Atomic blueprint that enforces a length.
bp_length <- Atomic$new("hello", "myBlueprint", 1L)

bp_length$compare(c("hi", "bye")) # FALSE
bp_length$compare("bye")          # TRUE
bp_length$compare(1)              # FALSE

## ------------------------------------------------
## Method `Atomic$bind`
## ------------------------------------------------

## Create an environment.
env <- new.env()

## Spawn a vector from a blueprint and bind the result to $name
## in env. We also lock the binding.
b <- Atomic$new(12.0, "vector", 1000L)$bind(env, TRUE)

## Trying to change value of a locked binding results in an error.
## Not run: env$vector <- 1.0

## You can later unlock the binding.
unlockBinding("vector", env)
env$vector <- "new value"

## Bind a prototype to $name within a list.
lst <- list(value = 1L)
b$bind(lst)
lst$vector

## ------------------------------------------------
## Method `Atomic$as_yaml`
## ------------------------------------------------

## Create an Atomic object.
ab <- Atomic$new(sample.int(10L), "randomValues", 10L)

## Create a simple YAML representation and print it.
cat(ab$as_yaml())

## Add additional headers to output.
myheaders <- list(author = "JM Potvin", date = "January 1st 2021")
cat(ab$as_yaml(headers = myheaders))

## Write output to a file.
path <- tempfile(fileext = ".yaml")
ab$as_yaml(file = path, headers = myheaders)

## Output is always encoded to UTF-8.
Encoding(ab$as_yaml(headers = list(utf8char = "`"))) == "UTF-8"

## You can pass additional parameters to yaml::as.yaml().
cat(ab$as_yaml(indent = 4L))

## Use custom handlers.
## Here, we use another handler for raw values.
handlers <- list(
    raw = function(x) { return(as.character(x)) }
)
ab$as_yaml(handlers = handlers)

## ------------------------------------------------
## Method `Atomic$as_json`
## ------------------------------------------------

## Create an Atomic object.
ab <- Atomic$new(sample.int(10L), "randomValues", 10L)

## Create a simple JSON representation and print it.
cat(ab$as_json())

## Add additional headers to output.
myheaders <- list(author = "JM Potvin", date = "January 1st 2021")
cat(ab$as_json(headers = myheaders))

## Write output to a file.
path <- tempfile(fileext = ".json")
ab$as_json(file = path, headers = myheaders)

## Output is always encoded to UTF-8.
Encoding(ab$as_json(headers = list(utf8char = "`"))) == "UTF-8"

## You can pass additional parameters to jsonlite::toJSON().
cat(ab$as_json(headers = list(test = 1.23456789)))
cat(ab$as_json(headers = list(test = 1.23456789), digits = 8L))

## ------------------------------------------------
## Method `Atomic$set`
## ------------------------------------------------

## Update $name. You could also update $length.
b <- Atomic$new(double(10L), "wrong-name")
b$set("name", "good-name")$print()

## Trying to update $type will throw an error.
## Not run: 
b$set("type", "raw")

## End(Not run)
b_new <- Atomic$new(raw(10L), "good-name")

jeanmathieupotvin/blueprint documentation built on Jan. 17, 2021, 10:54 a.m.