Learn R Programming

lfactors (version 1.0.4)

lfactor: lfactors

Description

lfactor creates a factor that can be compared to its levels or labels.

Usage

lfactor(x, levels, labels = levels, ...)

Arguments

x

a numeric or character vector of data. Levels of x can be taken either from levels or labels.

levels

a numeric vector of levels in x. Note that, unlike factor, these must be numeric.

labels

a vector of labels for the levels. This vector must be either characters that cannot be cast as numeric or characters that are equal to the level, of the same index, when cast as numeric.

arguments passed to factor

Value

An object of class lfactor that also implements factor

Details

An lfactor can be compared to the levels or the labels (see the Examples). Because of that, the levels must be numeric, and the labels must be either not castable as numeric or equal to the levels of the same index when cast as numeric.

An lfactor is, essentially, a factor that remembers the levels as well as the labels argument. Note that all of the arguments are passed to factor. Because lfactor imposes some additional constraints on the types of levels and labels and stores additional information, an lfactor uses more memory than a factor---because it stores both labels and levels---and is, in some ways, more limited than a factor.

See Also

factor

Examples

Run this code
# NOT RUN {
require(lfactors)
# make an example lfactor object
mon <- lfactor(1:12,
               levels=1:12,
               labels=c("Jan", "Feb", "Mar", "Apr", "May","Jun",
                        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))
# print out the lfactor
mon
# compare to label
mon == "Feb"
# Compare to level
mon == 2
# Show that the == works correctly
all.equal(mon == "Feb", mon == 2)
# Show that the != works correctly
all.equal(mon != "Feb", mon != 2)
# also works when the vector is not the lfactor
all.equal(mon[3] == c("Jan", "Feb", "Mar"), mon[3] == 1:3)

# or when both the lfactor and the object being compare to are vectors
all.equal(mon[1:2] == c("Feb", "Tuesday"), mon[1:2] == c(2,-4) )

# similar to Ops.factor, this gives a helpful warning and NA results
mon >= "Jan" 

# %in% works correctly
all.equal(mon %in% c(2, 3), mon %in% c("Feb", "Mar"))
# and when the lfactor is on the right
all.equal(c(-4, 14,3,10) %in% mon, c("not a month", "Third December","Mar","Oct") %in% mon)
# and when both left and right are lfactors
all.equal(mon %in% mon, rep(TRUE,12))
# }

Run the code above in your browser using DataLab