Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/krlmlr/scalar

Scalars
https://github.com/krlmlr/scalar

r

Last synced: 20 days ago
JSON representation

Scalars

Awesome Lists containing this project

README

        

---
output: github_document
---

```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.path = "man/figures/README-",
out.width = "100%"
)
library(tidyverse)
pkgload::load_all()
```

# scalar

[![Lifecycle: experimental](https://img.shields.io/badge/lifecycle-experimental-orange.svg)](https://www.tidyverse.org/lifecycle/#experimental)

The goal of scalar is to provide a [vctrs](https://vctrs.r-lib.org/) compatible way to indicate that a vector is intended to have length one.

## Installation

You can install the released version of scalar from [CRAN](https://CRAN.R-project.org) with:

``` r
install.packages("scalar")
```

## Example

This class is useful to distinguish between scalars and vectors when creating one-row tibbles that contain arbitrary objects, e.g. results of `rowwise()`-like computations.

```{r example}
library(scalar)

wrap_unless_scalar <- function(x) {
if (is_scalar(x)) return(x)
list(x)
}

tibble_row <- function(...) {
lst <- tibble::lst(...)
row <- purrr::map(lst, wrap_unless_scalar)
tibble(!!!row)
}

tibble_row(a = 1, b = 2:3, c = list(4))
tibble_row(a = scalar(1), b = 2:3, c = scalar(list(4)))
```

Non-scalars are rejected. Concatenation returns a "bare" object.

```{r example2, error = TRUE}
scalar(1:2)
vec_c(scalar(1), scalar(2))
```