Repository navigation
Expand file tree
/
Copy pathtables.R
More file actions
213 lines (169 loc) · 7.37 KB
/
Copy pathtables.R
File metadata and controls
213 lines (169 loc) · 7.37 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
#' Create a one way data table
#'
#' `tbl_1var()` creates a table giving counts and percentages on one variable.
#'
#' @param data A data frame.
#' @param formula The variable to tabulate. Should be given in formula notation, `~var`.
#' @param digits The number of digits to round to. Defaults to 3.
#' @param caption An optional caption for the table. Defaults to `NULL`, but a sensible default is
#' provided within the function.
#' @param with_prop Should proportions be supplied with instead of percents? Defaults to "no",
#' could also be "yes".
#' @param na_rm Should missing values be removed? Defaults to TRUE.
#'
#' @returns An object of class flextable. If in an interactive session, the table will be
#' viewable immediately.
#' @export
#'
#' @examples
#' tbl_1var(mtcars, ~gear)
#' tbl_1var(mtcars, ~gear, digits = 2)
#'
#' # Will give an error
#' try(tbl_1var(mtcars, ~Gear))
tbl_1var <- function(data, formula, digits = 3, caption = NULL, with_prop = c("no", "yes"), na_rm = TRUE) {
# check for empty strings and make them actual NAs
data <- tibble::as_tibble(data) %>%
dplyr::mutate(dplyr::across(dplyr::where(is.character), ~dplyr::na_if(., "")))
# error catching
check_test(mosaic::tally(formula, data = data, format = "count"))
with_prop <- base::match.arg(with_prop)
na <- find_na(data, formula)
# code
var <- formula[[2]]
var_str <- base::deparse(base::substitute(var))
if (na_rm == TRUE) {
data <- data %>%
dplyr::select({{ var }}) %>%
stats::na.omit()
}
if (base::is.null(caption)) {
caption <- base::paste("One Way Counts on Variable", var_str, "\n", "Missing:", na)
} else {
caption <- base::paste(caption, "\n", "Missing:", na)
}
if (with_prop == "no") {
output <- mosaic::tally(formula, data = data, format = "count") %>%
tibble::as_tibble() %>%
dplyr::mutate(pct = (n / base::nrow(data))*100) %>%
janitor::adorn_totals("row") %>%
finalize_tbl(digits = digits, caption = base::paste(caption, "\nNAs Removed: ", base::ifelse(na_rm == FALSE, "No", "Yes"))) %>%
flextable::set_header_labels(n = "Count", pct = "Percent") %>%
flextable::fontsize(size = 9, part = "all") %>%
fit_tbl()
} else if (with_prop == "yes") {
output <- mosaic::tally(formula, data = data, format = "count") %>%
tibble::as_tibble() %>%
dplyr::mutate(pct = (n / base::nrow(data))) %>%
janitor::adorn_totals("row") %>%
finalize_tbl(digits = digits, caption = base::paste(caption, "\nNAs Removed: ", base::ifelse(na_rm == FALSE, "No", "Yes"))) %>%
flextable::set_header_labels(n = "Count", pct = "Proportion") %>%
flextable::fontsize(size = 9, part = "all") %>%
fit_tbl()
}
output
}
#' Create a two way data table
#'
#' @inheritParams tbl_1var
#' @param formula The variables to tabulate. Should be given in formula notation `var1~var2`. Changing
#' the order of the variables will swap the table axes.
#' @param row_pct Should row percents be included in each cell? Defaults to "hide" with the only
#' other possible value being "show".
#'
#' @return An object of class flextable. If in an interactive session, the table will be
#' viewable immediately.
#' @export
#'
#' @examples
#' tbl_2var(mtcars, cyl~gear)
#' tbl_2var(mtcars, cyl~gear, row_pct = "show")
#' tbl_2var(mtcars, cyl~gear, caption = "This is the new caption")
#'
#' # Will give an error
#' try(tbl_2var(mtcars, Cyl~Gear))
tbl_2var <- function(data, formula, row_pct = c("hide", "show"), digits = 3, caption = NULL, na_rm = TRUE) {
# check for empty strings and make them actual NAs
data <- tibble::as_tibble(data) %>%
dplyr::mutate(dplyr::across(dplyr::where(is.character), ~dplyr::na_if(., "")))
# error catching
check_test(mosaic::tally(formula, data = data))
row_pct <- base::match.arg(row_pct)
na <- find_na(data, formula, n = 2)
# code
var1 <- formula[[2]]
var2 <- formula[[3]]
var1_str <- base::deparse(base::substitute(var1))
var2_str <- base::deparse(base::substitute(var2))
if (na_rm == TRUE) {
data <- data %>%
dplyr::select({{ var1 }}, {{ var2 }}) %>%
stats::na.omit()
}
if (base::is.numeric(data[, var1_str])) {
var1_lvls <- base::length(base::unique(data[, var1_str]))
} else {
var1_lvls <- base::nrow(base::unique(data[, var1_str]))
}
# table with no row percents
if (row_pct == "hide") {
if (base::is.null(caption)) {
caption <- base::paste("Two-Way Counts of", var1, "vs.", var2, "\n", var1_str, "Missing:", na[[1]],
"|", var2_str, "Missing:", na[[2]])
} else {
caption <- base::paste(caption, "\n", var1_str, "Missing:", na[[1]],
"|", var2_str, "Missing:", na[[2]])
}
starter <- mosaic::tally(formula, data = data) %>%
tibble::as_tibble() %>%
tidyr::pivot_wider(names_from = {{ var1 }}, values_from = n) %>%
janitor::adorn_totals(c("col", "row")) %>%
dplyr::mutate(Total = base::as.integer(Total))
starter %>%
finalize_tbl(digits = digits, caption = base::paste(caption, "\nNAs Removed:", base::ifelse(na_rm == FALSE, "No", "Yes"))) %>%
flextable::add_header_row(values = c("", var1_str, ""),
colwidths = c(1, var1_lvls, 1)) %>%
flextable::vline(j = c(1, var1_lvls + 1),
border = officer::fp_border(width = 1.5)) %>%
flextable::hline(i = nrow(starter) - 1,
border = officer::fp_border(width = 1.5)) %>%
flextable::hline(i = 1, part = "header") %>%
flextable::hline(i = 1, j = c(1, var1_lvls + 2), part = "header",
border = officer::fp_border(color = NA)) %>%
flextable::bold(j = 1) %>%
flextable::fontsize(size = 9, part = "all") %>%
fit_tbl()
}
# table with row percentages
else if (row_pct == "show") {
if (base::is.null(caption)) {
caption <- base::paste("Two-Way Counts (with Row Percentages) of", var1, "vs.", var2, "\n", var1_str, "Missing:", na[[1]],
"|", var2_str, "Missing:", na[[2]])
} else {
caption <- base::paste(caption, "\n", var1_str, "Missing:", na[[1]],
"|", var2_str, "Missing:", na[[2]])
}
starter <- mosaic::tally(formula, data = data) %>%
tibble::as_tibble() %>%
tidyr::pivot_wider(names_from = {{ var1 }}, values_from = n) %>%
janitor::adorn_totals(c("col", "row")) %>%
janitor::adorn_percentages("row") %>%
janitor::adorn_pct_formatting(digits = 2) %>%
janitor::adorn_ns(position = "front") %>%
dplyr::mutate(dplyr::across(-1, ~sub(" ", "\n", .)))
starter %>%
finalize_tbl(digits = digits, caption = base::paste(caption, "\nNAs Removed:", base::ifelse(na_rm == FALSE, "No", "Yes"))) %>%
flextable::add_header_row(values = c("", var1_str, ""),
colwidths = c(1, var1_lvls, 1)) %>%
flextable::vline(j = c(1, var1_lvls + 1),
border = officer::fp_border(width = 1.5)) %>%
flextable::hline(i = nrow(starter) - 1,
border = officer::fp_border(width = 1.5)) %>%
flextable::hline(i = 1, part = "header") %>%
flextable::hline(i = 1, j = c(1, var1_lvls + 2), part = "header",
border = officer::fp_border(color = NA)) %>%
flextable::bold(j = 1) %>%
flextable::fontsize(size = 9, part = "all") %>%
fit_tbl()
}
}