Encapsulated Classes with Reference Semantics

Creates classes with reference semantics, similar to R's built-in reference classes. Compared to reference classes, R6 classes are simpler and lighter-weight, and they are not built on S4 classes so they do not require the methods package. These classes allow public and private members, and they support inheritance, even when the classes are defined in different packages.

Build Status

R6 is an implemention of encapsulated object-oriented programming for R, and is a simpler, faster, lighter-weight alternative to R's built-in reference classes. This style of programming is also sometimes referred to as classical object-oriented programming.

Some features of R6:

  • R6 objects have reference semantics.
  • R6 cleanly supports inheritance across packages.
  • R6 classes have public and private members.

In contrast to R's reference classes, R6 is not built on the S4 class system, so it does not require the methods package. Unlike reference classes, R6 classes can be cleanly inherited across different packages.

See the Introduction article for usage examples.

To install R6 from CRAN:


To install the development version (requires the devtools package):

devtools::install_github('r-lib/R6', build_vignettes = FALSE)


Why R6?

Why the name R6? When R's reference classes were introduced, some users, following the names of R's existing class systems S3 and S4, called the new class system R5 in jest. Although reference classes are not actually called R5, the name of this package and its classes takes inspiration from that name.

The name R5 was also a code-name used for a different object system started by Simon Urbanek, meant to solve some issues with S4 relating to syntax and performance. However, the R5 branch was shelved after a little development, and it was never released.


R6 2.4.0

  • Fixed #146: Finalizers can now be private methods. (#181)

  • Fixed #167: Finalizers now run on cloned objects. (#180)

R6 2.3.0

  • Vignettes are no longer included as part of the source package because of their large size. Documentation is now at https://r6.r-lib.org/.

  • Fixed #125: The print.R6 method now always returns the object that was passed to it.

  • Fixed #155: In some cases, a cloned object's methods could refer to the wrong super object. (#156)

  • Fixed #94, #133: When cloning an object which contained a function that is not a method, the corresponding function in the new object would have its environment changed, as though it were a method. Now it no longer has a changed environment. (#156)

  • Fixed #121: If a finalize method was present, it would prevent objects passed to initialize from getting GC'd.

  • Fixed #158: If a $set method of an R6 generator object is given the value NULL, it previously removed the named item. Now it adds the named item with the value NULL.

  • Fixed #159: Printing an R6 object containing a large vector was slow.

R6 2.2.2

  • Fixed #108: When an object with a super object and an active binding in the super object was cloned, the new object's super object did not get the active binding -- it was a normal function.

  • Fixed #119: When a class had two levels of inheritance, an instance of that class's super object could contain methods that had an incorrect enclosing environment.

R6 2.2.1

  • Vignettes now only try use the microbenchmark package if it is present. This is so that the package builds properly on platforms where microbenchmark is not present, like Solaris.

  • Fixed ending position for trim().

R6 2.2.0

  • Classes can define finalizers explicitly, by defining a public finalize method. (#92, #93)

  • Added function is.R6() and is.R6Class(). (#95)

  • Fixed #96: R6 now avoids using $ and [[ after the class has been assigned to the object. This allows the user to provide their own methods for $ and [[ without causing problems to R6's operation.

R6 2.1.3

  • The plot S3 method for R6 objects will call $plot on the object if present. (#77)

  • Fixed printing of members that are R6 objects. (#88)

  • Fixed deep cloning for non-portable classes. (#85)

  • Added as.list.R6 method. (#91)

R6 2.1.2

  • Implemented format.R6() and format.R6ClassGenerator, the former calls a public format method if defined. This might change the functionality of existing classes that define a public format method intended for other purposes (#73. Thanks to Kirill Müller)

  • Functions are shown with their interface in print and format, limited to one line (#76. Thanks to Kirill Müller)

  • R6 objects and generators print out which class they inherit from. (#67)

R6 2.1.1

  • Fixed a bug with printing R6 objects when a [[ method is defined for the class. (#70)

  • Fixed cloning of objects that call a super method which accesses private. (#72)

R6 2.1.0

  • Added support for making clones of R6 objects with a clone() method on R6 objects. The deep=TRUE option allows for making clones that have copies of fields with reference semantics (like other R6 objects). (#27)

  • Allow adding public or private members when there were no public or private members to begin with. (#51)

  • Previously, when an R6 object was printed, it accessed (and called) active bindings. Now it simply reports that a field is an active binding. (#37, #38. Thanks to Oscar de Lama)

  • Printing private members now works correctly for portable R6 objects. (#26)

  • The 'lock' argument has been renamed to 'lock_objects'. Also, there is a new argument, 'lock_class', which can prevent changes to the class. (#52)

  • Fixed printing of NULL fields.

R6 2.0.1

  • A superclass is validated on object instantation, not on class creation.

  • Added debug and undebug methods to generator object.

R6 2.0

  • [BREAKING CHANGE] Added portable option, which allows inheritance across different package namespaces, and made it the default.

  • Added set() method on class generator object, so new fields and methods can be added after the generator has been created.

  • All of the functions involved in instantiating objects are encapsulated in an environment separate from the R6 namespace. This means that if a generator is created with one version of R6, saved, then restored in a new R session that has a different version of R6, there shouldn't be any problems with compatibility.

  • Methods are locked so that they can't be changed. (Fixes #19)

  • Inheritance of superclasses is dynamic; instead of reading in the superclass when a class is created, this happens each time an object is instantiated. (Fixes #12)

  • Added trailing newline when printing R6 objects. (Thanks to Gabor Csardi)

  • The print method of R6 objects can be redefined. (Thanks to Gabor Csardi)

R6 1.0.1

  • First release on CRAN.

  • Removed pryr from suggested packages.

R6 1.0

  • First release

Reference manual

It appears you don't have a PDF plugin for this browser. You can click here to download the reference manual.


2.5.1 by Winston Chang, 2 months ago

https://r6.r-lib.org, https://github.com/r-lib/R6/

Report a bug at https://github.com/r-lib/R6/issues

Browse source code at https://github.com/cran/R6

Authors: Winston Chang [aut, cre]

Documentation:   PDF Manual  

MIT + file LICENSE license

Suggests testthat, pryr

Imported by AIPW, ASSISTant, AzureAuth, AzureContainers, AzureGraph, AzureKeyVault, AzureKusto, AzureRMR, AzureStor, AzureVM, CVXR, D2MCS, DBItest, DTSg, DataFakeR, DataSpaceR, Dict, DoubleML, GREMLINS, GauPro, GeoFIS, GeoMongo, Ghost, IGP, KGode, LFDREmpiricalBayes, LIHKGr, LifeInsuranceContracts, MGDrivE, MLVSBM, Microsoft365R, NNbenchmark, ODataQuery, OpenImageR, PLNmodels, PTXQC, PetfindeR, PlackettLuce, PlaneGeometry, QuantTools, R6DS, R6P, R6causal, RBaseX, RDML, RGF, RKEEL, ROOPSD, RSQL, RestRserve, RonFHIR, SACOBRA, SAR, StabilizedRegression, SuperGauss, SuperpixelImageSegmentation, TOSTER, VarBundle, almanac, anndata, anybadger, argparse, arrangements, arrow, basictabler, batchtools, bbotk, bdpar, beakr, bender, blandr, bootGOF, cabinets, callr, cape, carbonate, casino, charlatan, choroplethr, cicerone, cliapp, clustermq, cometr, comparer, conditionz, conflr, connectwidgets, conos, container, corpustools, covidregionaldata, criticalpath, crosstalk, crossword.r, crul, cvcqv, cwbtools, dash, data.tree, data.validator, datapackage.r, datastepr, dbnR, dbplyr, deepregression, delayed, desc, dictionar6, dipsaus, distcomp, distr6, dockerfiler, dplyr, earthtide, elastic, elementR, eplusr, erratum, fabletools, factset.analyticsapi.engines, fauxpas, fcaR, fiery, file2meco, firebase, flipr, fuzzywuzzyR, ganalytics, geojsonR, geometa, geonapi, geosapi, ggExtra, ggPMX, ghql, glmmsr, glow, gnn, gqlr, greta, guiplot, hadron, hakaiApi, hdf5r, hesim, hipread, hoardr, homomorpheR, httpuv, httr, httr2, huxtable, iml, individual, influxdbclient, ipc, ipumsr, irace, isqg, jackalope, jmv, jmvcore, jrc, keras, keyring, kibior, knitrProgressBar, languageserver, lazyarray, lazybar, leabRa, leafdown, lgr, lifelogr, linne, lmtp, log, lslx, lumberjack, luz, mRpostman, mcboost, mcparallelDo, medmod, meltr, metacoder, microeco, missSBM, mkin, mlapi, mlr3, mlr3benchmark, mlr3cluster, mlr3db, mlr3filters, mlr3fselect, mlr3hyperband, mlr3learners, mlr3misc, mlr3oml, mlr3pipelines, mlr3proba, mlr3spatiotempcv, mlr3tuning, mlr3tuningspaces, mlrintermbo, mstrio, multidplyr, multiverse, ncodeR, neo4r, newsmd, nimble, nmslibR, noah, ocs4R, odin, officer, onelogin, onlineforecast, oolong, ooplah, openSkies, openmetrics, orderly, osqp, otp, ows4R, pagoda2, pagoo, pak, paleopop, palm, paradox, param6, particle.swarm.optimisation, pathlibr, patternplot, percentiles, pguIMP, piecepackr, pivottabler, pkgbuild, pkgcache, pkgdepends, pkgnet, plumber, poems, poio, polished, pool, powerly, prcbench, processx, progress, promises, r6extended, rENA, raveio, rbedrock, rbit, rchess, rcmdcheck, rcrossref, rdecision, rdhs, rdoc, readr, rearrr, redux, reqres, request, retistruct, rgbif, rgee, rgoogleslides, rhub, rim, ring, rlc, rly, rminizinc, rodeo, rotor, routr, roxygen2, rsdmx, rstack, rtext, rtson, sFFLHD, sass, sbm, scales, scatr, selectr, semverutils, set6, shiny, shiny.i18n, shiny.reglog, shiny.semantic, shiny.worker, shinyloadtest, shinymanager, shinyreforms, shinytest, shopifyr, sofa, solitude, solrium, sourceR, spsComps, spsUtil, stoRy, stockfish, storr, strand, table.express, tableschema.r, targets, taxa, taxize, teamr, telegram, telegram.bot, testthat, text2vec, textTinyR, theiaR, thor, threeBrain, thriftr, tidygraph, timeR, torch, tsibbletalk, twenty48, txtq, unstruwwel, valuer, vaultr, vcr, vmd, vstsr, wactor, waiter, walrus, webdriver, webmockr, websocket, wilson, wyz.code.offensiveProgramming, wyz.code.rdoc, wyz.code.testthat, zen4R.

Depended on by AlphaSimR, BLRPM, ConfigParser, DSI, DSLite, LightningR, SeqExpMatch, ShinyImage, bggAnalytics, blatent, gpboost, resourcer, smartR, superml, tangram.

Suggested by DataVisualizations, R62S3, aoos, backpipe, box, checkmate, covr, debugme, grobblR, leaflet, mockery, prompt, ps, r2d3, r6methods, renv, sparklyr, waldo, zip.

See at CRAN