reverse.RdSimple literal reversal. Will stop with an error message if x is not a factor (or ordered) variable.
reverse(x, eol = c("Skip", "DNP"))a new factor variable with reversed values
Sometimes people want to reverse some levels, excluding others and leaving them at the end of the list. The "eol" argument sets aside some levels and puts them at the end of the list of levels.
The use case for the eol argument is a factor
with several missing value labels, as appears in SPSS. With
up to 18 different missing codes, we want to leave them
at the end. In the case for which this was designed, the
researcher did not want to designate those values as
missing before inspecting the pattern of observed values.
## Consider alphabetication of upper and lower
x <- factor(c("a", "b", "c", "C", "a", "c"))
levels(x)
#> [1] "C" "a" "b" "c"
xr1 <- reverse(x)
xr1
#> [1] a b c C a c
#> Levels: c b a C
## Keep "C" at end of list, after reverse others
xr2 <- reverse(x, eol = "C")
xr2
#> [1] a b c C a c
#> Levels: c b a C
y <- ordered(x, levels = c("a", "b", "c", "C"))
yr1 <- reverse(y)
class(yr1)[1] == "ordered"
#> [1] TRUE
yr1
#> [1] a b c C a c
#> Levels: C < c < b < a
## Hmm. end of list amounts to being "maximal".
## Unintended side-effect, but interesting.
yr2 <- reverse(y, eol = "C")
yr2
#> [1] a b c C a c
#> Levels: c < b < a < C
## What about a period as a value (SAS missing)
z <- factor(c("a", "b", "c", "b", "c", "."))
reverse(z)
#> [1] a b c b c .
#> Levels: c b a .
z <- factor(c(".", "a", "b", "c", "b", "c", "."))
reverse(z)
#> [1] . a b c b c .
#> Levels: c b a .
## How about R NA's
z <- factor(c(".", "a", NA, "b", "c", "b", NA, "c", "."))
z
#> [1] . a <NA> b c b <NA> c .
#> Levels: . a b c
reverse(z)
#> [1] . a <NA> b c b <NA> c .
#> Levels: c b a .
z <- ordered(c(".", "a", NA, "b", "c", "b", NA, "c", "."))
z
#> [1] . a <NA> b c b <NA> c .
#> Levels: . < a < b < c
str(z)
#> Ord.factor w/ 4 levels "."<"a"<"b"<"c": 1 2 NA 3 4 3 NA 4 1
## Put "." at end of list
zr <- reverse(z, eol = ".")
zr
#> [1] . a <NA> b c b <NA> c .
#> Levels: c < b < a < .
str(zr)
#> Ord.factor w/ 4 levels "c"<"b"<"a"<".": 4 3 NA 2 1 2 NA 1 4
z <- ordered(c(".", "c", NA, "e", "a", "c", NA, "e", "."),
levels = c(".", "c", "e", "a"))
reverse(z, eol = ".")
#> [1] . c <NA> e a c <NA> e .
#> Levels: a < e < c < .
reverse(z, eol = c("a", "."))
#> [1] . c <NA> e a c <NA> e .
#> Levels: e < c < a < .