as_factor: Convert Select 'numform' Outputs to Factor

Description Usage Arguments Value Examples

View source: R/as_factor.R

Description

Convert month and weekday and weekday types to factor with correctly ordered levels. Note that the 'forcats' package imported by the 'tidyverse' package, has an as_factor function that can compete with numform's version. If in doubt, prefix with numform::as_factor.

Usage

1
as_factor(x, shift = 0, ...)

Arguments

x

A vector of weekdays or months.

shift

Shift the levels to the right or left. Useful for setting the week beginning to something besides Sunday. Use -1 to set to Monday instead.

...

ignored.

Value

Returns a factor vector with levels set.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
dat <- structure(list(month1 = c("Jan", "Nov", "Mar", "Jul", "Aug",
"Jan", "Aug", "May", "Dec", "Apr"), month2 = c("March", "May",
"March", "July", "May", "October", "March", "November", "April",
"January"), weekday1 = c("Th", "F", "M", "Su", "Th", "Su", "M",
"Th", "W", "T"), weekday2 = c("We", "Th", "Fr", "Sa", "We", "Su",
"Tu", "Su", "Su", "Th"), weekday3 = c("Sat", "Wed", "Mon", "Wed",
"Wed", "Wed", "Wed", "Sun", "Fri", "Thu"), weekday4 = c("Sunday",
"Sunday", "Thursday", "Saturday", "Monday", "Wednesday", "Friday",
"Thursday", "Sunday", "Saturday")), .Names = c("month1", "month2",
"weekday1", "weekday2", "weekday3", "weekday4"))

## Note that the 'forcats' package imported by the 'tidyverse' package, has an
## `as_factor` function that can compete with numform's version.  If in doubt
## prefix with `numform::as_factor`
as_factor(dat$month1)
as_factor(dat$month2)
as_factor(dat$weekday1)
as_factor(dat$weekday2)
as_factor(dat$weekday3)
as_factor(dat$weekday4)

## shift levels
as_factor(dat$weekday4, -1)
as_factor(dat$weekday4, -2)
as_factor(dat$weekday4, 1)
as_factor(dat$weekday4, 2)

## Not run: 
library(tidyverse)

data_frame(
    revenue = rnorm(10000, 500000, 50000),
    date = sample(seq(as.Date('1999/01/01'), as.Date('2000/01/01'), by="day"), 10000, TRUE),
    site = sample(paste("Site", 1:5), 10000, TRUE)
) %>%
    mutate(
        dollar = f_comma(f_dollar(revenue, digits = -3)),
        thous = f_thous(revenue),
        thous_dollars = f_thous(revenue, prefix = '$'),
        abb_month = f_month(date),
        abb_week = numform::as_factor(f_weekday(date, distinct = TRUE))
    ) %T>%
    print() %>%
    ggplot(aes(abb_week, revenue)) +
        geom_jitter(width = .2, height = 0, alpha = .2) +
        scale_y_continuous(label = ff_thous(prefix = '$'))+
        facet_wrap(~site) +
        theme_bw()

## End(Not run)

trinker/numform documentation built on Oct. 12, 2021, 11:17 a.m.