knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "README-" ) library(refactor, warn.conflicts = FALSE)
refactor is an R package which aims to provide better handling of factors. Though R does have a special data type for factors, it isn't always explicity catered for in commonly used R functions, which can lead to unexpected and undesirable outcomes (e.g. see this Win-Vector blog post). This observation formed the inspiration for 're'-factor: which is essentially to 're'-visit functions likely to be used with factor data and where possible to wrap, extend or override them in order to better cater for factor data, or at the very least to provide warnings when the integrity of the data could be compromised by an operation.
refactor is not available on CRAN but you can easily install the latest development version from github using devtools
:
# install.packages("devtools") devtools::install_github("jonmcalder/refactor")
Below are a few examples to illustrate some scenarios in which refactor can improve on base R's handling of factors.
Please see the vignette for more details: vignette("refactor", package = "refactor")
cfactor()
string <- c("a", "b", "c") factor(string, levels = c("b", "c", "d")) cfactor(string, levels = c("b", "c", "d"))
hard_to_detect <- c("EUR 21 - EUR 22", "EUR 100 - 101", "EUR 1 - EUR 10", "EUR 11 - EUR 20") factor(hard_to_detect, ordered = TRUE) cfactor(hard_to_detect, ordered = TRUE)
cut
method to handle (discrete) integer datagenerate 'natural' intervals for factors when using cut on integer vectors
[1,3], [4,6], [7,9]
as opposed to (0.5, 3.5], (3.5, 6.5], (6.5, 9.5]
label factor levels more intuitively
1-3, 4-6, 7-9
as opposed to [1,3], [4,6], [7,9], or (0,3], (3,6], (6-9]
x_int <- 1:9 cut.default(x_int, breaks = 3) cut(x_int, breaks = 3)
cut
method to handle (non-numeric) ordered datacut
usually requires numeric data, but refactor extends cut
to handle other ordered datasome_letters <- factor(c('d','e','f','a','b','c','g','h','i'), ordered = TRUE) cut(some_letters, breaks = c('a','c','f','i'), include.lowest = TRUE, ordered_result = TRUE)
Suggestions and feedback are most welcome.
Feel free to open an issue if you want to request a feature or report a bug, and make a pull request if you can contribute.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.