library(magrittr) # library(sticky)
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"" behavior is often undesirable. It is tedious to try manage attribute across these operations. It leads to confusion, boilerplate code and source for errors.
The sticky
package alleviates this shortcomings by providing a simple mechanism for preserving attributes. By marking objects sticky
, attributes become resilient 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
library(sticky)
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
If all elements of a list or a data.frame need to behave in a sticky manner,
use sticky_all
.
df <- sticky_all(df) attr( df[2:3,"nonstick"], 'foo' ) # Now 'baz'
install.packages('sticky')
libraty(devtools) lnstall_github('decisionpatterns/sticky')
There are a number of things that can be done with sticky
:
The issue of attribute resilience has been often asked and debated. Here are a few of the most prevalent discussions.
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.