1+ # ' Convert frequency or case form data into table form
2+ # '
3+ # ' Converts object (`obj`) in frequency or case form into table form. `freq`
4+ # ' must be supplied if `obj` is in frequency form.
5+ # '
6+ # ' @param obj object to be converted to table form
7+ # ' @param freq If `obj` is in frequency form, this is the name of the frequency column. Leave as `NULL` if `obj` is in case form.
8+ # ' @param dims A list of table dimensions. If not specified, all variables apart from `freq` will be used as dimensions
9+ # ' @return object in table form
10+ # '
11+ # ' @details
12+ # ' If `obj` was in table form to begin with, it is simply returned to the user
13+ # ' as-is.
14+ # '
15+ # '
16+ # ' @examples
17+ # ' \dontrun{
18+ # ' data("HairEyeColor")
19+ # ' freqForm <- as.data.frame(HairEyeColor) # Generate frequency form data
20+ # ' tidy_freqForm <- as_tibble(HairEyeColor) # Generate tidy frequency form data
21+ # ' caseForm <- expand.dft(freqForm) # Generate case form data
22+ # '
23+ # ' as_table(freqForm, freq = "Freq") # frequency -> table form
24+ # ' as_table(freqForm) # Warned if forgot freq
25+ # ' as_table(caseForm) # case form -> table form
26+ # '
27+ # ' # For specific dimensions
28+ # ' as_table(tidy_freqForm, freq = "n", dims = c("Hair", "Eye"))
29+ # ' }
30+ # '
31+ # ' @importFrom stats reformulate xtabs
32+ # ' @export
33+
34+ as_table <- function (obj , freq = NULL , dims = NULL ){
35+
36+ # If user supplied a table already, return it back to them
37+ if (length(intersect(" table" , class(obj ))) > 0 ){
38+ return (obj )
39+ }
40+
41+ # If obj is a tibble, convert to data frame
42+ if (length(intersect(" tbl" , class(obj ))) > 0 ){
43+ obj <- as.data.frame(obj )
44+ }
45+
46+ if (! is.null(dims )){ # If dims supplied by user, use those
47+ cols <- dims
48+ }
49+ else { # If dims NOT supplied by user, use everything else
50+ cols <- colnames(obj )
51+ }
52+
53+ if (! is.null(freq )){ # If freq supplied by user, then... (freq form)
54+ cols <- cols [cols != freq ] # Remove freq column
55+ tab <- xtabs(reformulate(cols , response = freq ), data = obj ) # freq ~ cols
56+ }
57+ else { # If freq NOT supplied by user, then... (case form)
58+ tab <- xtabs(reformulate(cols ), data = obj )
59+
60+ # Check if user forgot to supply freq, warn if they potentially forgot
61+ common <- c(" n" , " freq" , " frequency" , " count" )
62+ if (length(intersect(tolower(colnames(obj )), common )) > 0 ){
63+ warning(" Ensure a value for 'freq' was supplied if your data was in frequency form." )
64+ }
65+ }
66+ return (tab )
67+ }
0 commit comments