In base R, an object's user-defined attributes are lost when common functions such as subset, extend, extract, etc. are used.[1] This is due to R's functional nature. The language is designed to encourage creating function that yield return values that are distinct from the inputs. While this often works well, the language has left attribute management to developers. The problem is, this “default”“ behaviour is often undesirable. It is tedious to try manage atttribute accross these operations. It leads to confusion, boilerplate code and source for errors.

The sticky package alleviates this shortcomings by providing a simple mechanism for preservince attributes. By marking objects sticky, attributes become resilent to the common data operations, e.g. subset/extend/append or when inserted into or extracted from recursive (list-like) objects such as data frames or data tables. 'sticky' works on both atomic and recursive objects.

This allows R object to behave similar to other object-oriented programming languages while retaining its functional nature. There isn't much to the package. The sticky function and it's complement, unstick are the only exported functions.

[1]: Non user-defined attributes include class and dimension


Here is an simple example of a sticky attribute in action. Under base R, attributes do not survive a slice/subset/[ operation:

x <- 1:5
attr(x, 'foo') <- 'bar'
attr(x[1:3],'foo')        # NULL -- attribute was lost by the subset

To ensure that the attributes get preserved, simply declare the object as sticky:

x <- sticky(x)
attr(x[1:3],'foo')        # 'bar' -- attribute preserved during subset

sticky() works for vectors inside table-like objects ( i.e. data.frames and data.tables), preserving their attributes during table operations.

    df <- data.frame( 
      sticky   = sticky( structure(1:5, foo="bar") ),
      nonstick = structure( letters[1:5], foo="bar" )
    attr( df[2:3,"nonstick"], 'foo' )  # NULL
    attr( df[2:3,"sticky"], 'foo' )    # bar


Stable Version: CRAN (coming soon)


Development Version: Github


Use Cases

There are a number of things that can be done with sticky:


The issue of attribute resilence has been often asked and debated. Here are a few of the most prevalent discussions.