https://github.com/cynkra/struct
  
  
    Strict modification of objects 
    https://github.com/cynkra/struct
  
        Last synced: 3 months ago 
        JSON representation
    
Strict modification of objects
- Host: GitHub
 - URL: https://github.com/cynkra/struct
 - Owner: cynkra
 - License: other
 - Created: 2024-02-19T11:38:11.000Z (over 1 year ago)
 - Default Branch: main
 - Last Pushed: 2025-06-03T17:33:56.000Z (5 months ago)
 - Last Synced: 2025-07-28T23:56:03.510Z (3 months ago)
 - Language: R
 - Size: 25.4 KB
 - Stars: 8
 - Watchers: 2
 - Forks: 1
 - Open Issues: 2
 - 
            Metadata Files:
            
- Readme: README.Rmd
 - License: LICENSE
 
 
Awesome Lists containing this project
- jimsghstars - cynkra/struct - Strict modification of objects (R)
 
README
          ---
output: github_document
---
```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "man/figures/README-",
  out.width = "100%"
)
```
# struct
{struct} provides ways to modify objects more strictly, guaranteeing that we
keep the type of the modified element, where type is defined by `vctrs::vec_ptype()`.
The `struct()` function gives a subclass "struct" to the objects if its internal
type is list (thus including data frames), and recursively to its list components.
When assigning new values, we give it the "struct" subclass if relevant then 
use `vctrs::vec_cast()` to check the compatibility of the input with the output,
and apply coercion if necessary.
## Installation
Install with:
``` r
remotes::install_github("cynkra/struct")
```
## Example
```{r, error = TRUE}
library(struct)
library(tibble)
x1 <- list(
  a = 1,
  b = list(tibble(c = 3:4, d = 5:6)),
  c = tibble(e = 7:8, f = 9:10),
  y = list(z = c("a", "b"))
)
x2 <- deep_struct(x1)
x2
print_tree(x2)
# works
x2$a <- 11
x2$b <- list(tibble(c = 13:14, d = 15:16))
x2$c <- tibble(e = 17:18, f = 19:20)
# fails
x2$a <- c(11, 12)
x2$a <- "a"
x2$b <- list("a", "b")
x2$c <- 1
x2[["z"]]
```