Ecosyste.ms: Awesome

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

Awesome Lists | Featured Topics | Projects

https://github.com/r-lib/sloop

S language OOP ⛵️
https://github.com/r-lib/sloop

r r6 s3 s4

Last synced: 3 months ago
JSON representation

S language OOP ⛵️

Awesome Lists containing this project

README

        

---
output: github_document
---

```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.path = "man/figures/README-"
)
```

# sloop sloop website

[![CRAN status](https://www.r-pkg.org/badges/version/sloop)](https://cran.r-project.org/package=sloop)
[![R-CMD-check](https://github.com/r-lib/sloop/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/r-lib/sloop/actions/workflows/R-CMD-check.yaml)
[![Codecov test coverage](https://codecov.io/gh/r-lib/sloop/branch/main/graph/badge.svg)](https://app.codecov.io/gh/r-lib/sloop?branch=main)

The goal of sloop is to provide tools to help you interactively explore and understand object oriented programming in R, particularly with S3.

Please note that unlike other [r-lib](https://github.com/r-lib) packages, sloop only works with R 3.3 and later.

## Installation

You can install sloop from github with:

```{r gh-installation, eval = FALSE}
# install.packages("pak")
pak::pak("r-lib/sloop")
```

## Usage

```{r setup}
library(sloop)
```

sloop provides a variety of tools for understanding how S3 works. The most useful is probably `s3_dispatch()`. Given a function call, it shows the set of methods that are considered, found, and actually called:

```{r}
s3_dispatch(print(Sys.time()))
```

To the best of my ability it covers all the details of S3 method dispatch including group generics, internal generics, implicit classes, and use of `NextMethod()` (indicated by `->`):

```{r}
# Implicit class
x <- matrix(1:6, nrow = 2)
s3_dispatch(print(x))

# Internal generic
length.numeric <- function(x) 10
s3_dispatch(length(x))

s3_dispatch(length(structure(x, class = "numeric")))

# NextMethod
s3_dispatch(Sys.Date()[1])

# group generic + NextMethod()
s3_dispatch(sum(Sys.Date()))
```

It also provides tools for determing what type of function or object you're dealing with:

```{r}
ftype(t)
ftype(t.test)
ftype(t.data.frame)

otype(1:10)
otype(mtcars)
otype(R6::R6Class()$new())
```

And for retrieving the methods associated with a generic or class:

```{r}
s3_methods_class("factor")

s3_methods_generic("summary")
```