Skip to content

Commit 8ee4cad

Browse files
committed
csv
1 parent e0b2876 commit 8ee4cad

72 files changed

Lines changed: 1749 additions & 2038 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

NEWS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ value of interest.
88
* Confidence intervals for numeric variables.
99
* Excel tables and charts! `set_opts( output = "excel", file = "my_workbook" )`
1010
* Improved conversion of tables to data frames with `as.data.frame()`.
11+
* The interface for CSV printing is now the same as for all other kinds of printing: `set_opts( output = "CSV", file = "my_file" )`
1112

1213
# surveytable 0.9.8
1314

R/as.data.frame.R

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
#'
2323
#' @examples
2424
#' set_survey(namcs2019sv)
25-
#' tab("AGER") |> as.data.frame()
25+
#' as.data.frame( tab("AGER") )
2626
as.data.frame.surveytable_table = function(x, ...) {
2727
class(x) = "data.frame"
2828
names(x) = make.names( names(x), unique = TRUE )

R/codebook.R

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,17 @@
11
#' Create a codebook for the survey
22
#'
33
#' @param all tabulate all the variables?
4-
#' @param csv name of a CSV file
54
#'
65
#' @return A list of tables.
76
#' @export
87
#'
98
#' @examples
109
#' set_survey(namcs2019sv)
1110
#' codebook()
12-
codebook = function(all = FALSE
13-
, csv = getOption("surveytable.csv")) {
11+
codebook = function(all = FALSE) {
1412
design = .load_survey()
1513
lret = list()
16-
lret[[1]] = set_survey(design, csv = csv)
14+
lret[[1]] = set_survey(design)
1715

1816
nn = names(design$variables)
1917
nr = nrow(design$variables)
@@ -81,7 +79,7 @@ codebook = function(all = FALSE
8179

8280
attr(ret, "title") = "Codebook"
8381
attr(ret, "num") = 5
84-
lret[[2]] = .write_out(ret, csv = csv)
82+
lret[[2]] = .finalize_tab(ret)
8583

8684
if (all) {
8785
op_ = options(surveytable.find_lpe = FALSE)
@@ -98,8 +96,7 @@ codebook = function(all = FALSE
9896
lret[[n1]] = tab(n1
9997
, test = FALSE
10098
, drop_na = FALSE
101-
, max_levels = Inf
102-
, csv = csv)
99+
, max_levels = Inf)
103100
attr(env$survey$variables[,ii], "label") = lbl0
104101
}
105102
}

R/set_opts.R

Lines changed: 41 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -35,34 +35,35 @@
3535
#' * `"Excel"`: print to an Excel workbook. Please specify the name of an Excel file using
3636
#' the `file` argument. Before using Excel printing, please be sure to install these
3737
#' packages: `openxlsx2` and `mschart`.
38+
#' * `"CSV"`: print to a comma-separated values (CSV) file. Please specify the name of a
39+
#' CSV file using the `file` argument.
3840
#'
3941
#' @param reset reset all options to their default values?
4042
#' @param mode `"general"` or `"NCHS"`. See below for details.
4143
#' @param adj adjustment to the Korn and Graubard confidence intervals for proportions. See
4244
#' `svyciprop_adjusted()` for details.
4345
#' @param output specify how the output is printed: `"auto"` (default); `"huxtable"`, `"gt"`, or
44-
#' `"kableExtra"`; `"raw"`; or `"Excel"`. If `output` is `"Excel"`: must also specify `file`; be
45-
#' sure to install `openxlsx2` and `mschart`.
46+
#' `"kableExtra"`; `"raw"`; `"Excel"` or `"CSV"`. If `output` is `"Excel"` or `"CSV"`, must also specify
47+
#' `file`. If `output` is `"Excel"`, be sure to install `openxlsx2` and `mschart`.
4648
#' @param file file name (see `output`).
4749
#' @param .file_temp place `file` in a temporary folder?
4850
#' @param count round counts to the nearest integer (`"int"`) or one thousand (`"1k"`).
4951
#' @param lpe identify low-precision estimates?
5052
#' @param drop_na drop missing values (`NA`)? Categorical variables only.
5153
#' @param max_levels a categorical variable can have at most this many levels.
5254
#' Used to avoid printing huge tables.
53-
#' @param csv the name of a CSV file or `""` to turn off CSV output.
5455
#'
5556
#' @return (Nothing.)
5657
#' @family options, print
5758
#' @export
5859
#'
5960
#' @examples
60-
#' # Send output to a CSV file:
61-
#' file_name = tempfile(fileext = ".csv")
62-
#' suppressMessages( set_opts(csv = file_name) )
6361
#' set_survey(namcs2019sv)
62+
#'
63+
#' # Round counts to the nearest one thousand:
64+
#' set_opts(count = "1k")
6465
#' tab("AGER")
65-
#' set_opts(csv = "") # Turn off CSV output
66+
#' set_opts(count = "int")
6667
#'
6768
#' show_opts()
6869
set_opts = function(
@@ -76,7 +77,6 @@ set_opts = function(
7677
, lpe = NULL
7778
, drop_na = NULL
7879
, max_levels = NULL
79-
, csv = NULL
8080
) {
8181

8282
#### !!! If making changes, update: .onLoad(), set_opts(), show_opts(), .check_options()
@@ -124,7 +124,7 @@ set_opts = function(
124124
if (!is.null(output)) {
125125
if (getOption("surveytable.print") == ".print_excel") .print_excel_finish()
126126

127-
output %<>% .mymatch(c("huxtable", "gt", "kableExtra", "auto", "raw", "excel"))
127+
output %<>% .mymatch(c("huxtable", "gt", "kableExtra", "auto", "raw", "excel", "csv"))
128128
if (output == "auto") {
129129
message("* Printing with huxtable for screen, gt for HTML, or kableExtra for PDF.")
130130
options(surveytable.raw = FALSE
@@ -140,26 +140,8 @@ set_opts = function(
140140
options(surveytable.raw = TRUE
141141
, surveytable.print = ".print_raw"
142142
, surveytable.file = "", surveytable.file_show = "")
143-
} else if (output == "excel") {
144-
assert_that(is.string(file), nzchar(file)
145-
, msg = "For Excel printing, please specify a file name using the file argument.")
146-
if (!endsWith(tolower(file), ".xlsx")) {
147-
file = glue("{file}.xlsx")
148-
}
149-
if (!isTRUE(.file_temp)) {
150-
file %<>% normalizePath(mustWork = FALSE)
151-
file_show = file
152-
} else {
153-
file = file.path(tempdir(), file)
154-
file_show = file %>% basename()
155-
}
156-
message(glue("* Printing to Excel workbook {file_show}."))
157-
if (file.exists(file)) {
158-
message("* NOTE: file already exists!")
159-
}
160-
options(surveytable.raw = FALSE
161-
, surveytable.print = ".print_excel"
162-
, surveytable.file = file, surveytable.file_show = file_show)
143+
} else if (output %in% c("excel", "csv")) {
144+
.set_output_file(output = output, file = file, .file_temp = .file_temp)
163145
}
164146
}
165147

@@ -206,21 +188,36 @@ set_opts = function(
206188
options(surveytable.max_levels = max_levels)
207189
}
208190

209-
if (!is.null(csv)) {
210-
assert_that(is.string(csv)
211-
, msg = "CSV file name must be a character string.")
212-
if (nzchar(csv)) {
213-
message(paste0("* Sending CSV output to: ", csv))
214-
if (file.exists(csv)) {
215-
message("* (File already exists. Output will be appended to the end of the file.)")
216-
}
217-
message("* To turn off CSV output: set_opts(csv = '')")
218-
} else {
219-
message("* Turning off CSV output.")
220-
}
221-
options(surveytable.csv = csv)
222-
}
223-
224191
.check_options()
225192
invisible(NULL)
226193
}
194+
195+
.set_output_file = function(output, file, .file_temp) {
196+
assert_that(output %in% c("excel", "csv"))
197+
type = switch(output
198+
, excel = "Excel"
199+
, csv = "CSV")
200+
extension = switch(output
201+
, excel = ".xlsx"
202+
, csv = ".csv")
203+
assert_that(is.string(file), nzchar(file)
204+
, msg = glue("For {type} printing, please specify a file name using the file argument."))
205+
if (!endsWith(tolower(file), extension)) {
206+
file = glue("{file}{extension}")
207+
}
208+
if (!isTRUE(.file_temp)) {
209+
file %<>% normalizePath(mustWork = FALSE)
210+
file_show = file
211+
} else {
212+
file = file.path(tempdir(), file)
213+
file_show = file %>% basename()
214+
}
215+
message(glue("* Printing to {type} file {file_show}."))
216+
if (file.exists(file)) {
217+
message("* NOTE: file already exists!")
218+
}
219+
options(surveytable.raw = FALSE
220+
, surveytable.print = glue(".print_{output}")
221+
, surveytable.file = file, surveytable.file_show = file_show)
222+
}
223+

R/set_survey.R

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
#'
1111
#' @param design a survey object, created with [survey::svydesign()] or
1212
#' [survey::svrepdesign()]. For an unweighted survey, a `data.frame` or similar.
13-
#' @param csv name of a CSV file
1413
#' @param ... arguments to [set_opts()].
1514
#'
1615
#' @family options
@@ -20,7 +19,7 @@
2019
#' @examples
2120
#' set_survey(namcs2019sv)
2221
#' set_survey(namcs2019sv, mode = "general")
23-
set_survey = function(design, csv = getOption("surveytable.csv"), ...) {
22+
set_survey = function(design, ...) {
2423
# In case there's an error below and we don't set a new survey,
2524
# don't retain the previous survey either.
2625
env$survey = NULL
@@ -107,7 +106,7 @@ set_survey = function(design, csv = getOption("surveytable.csv"), ...) {
107106
env$survey = design
108107

109108
.check_options()
110-
.write_out(out, csv = csv)
109+
.finalize_tab(out)
111110
}
112111

113112
.load_survey = function() {

R/show_opts.R

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ show_opts = function() {
2626
, ".print_auto" = "* Printing with huxtable for screen, gt for HTML, or kableExtra for PDF."
2727
, ".print_raw" = "* Generating unformatted / raw output."
2828
, ".print_excel" = glue("* Printing to Excel workbook {getOption('surveytable.file_show')}.")
29+
, ".print_csv" = glue("* Printing to CSV file {getOption('surveytable.file_show')}.")
2930
, glue("* Printing with a custom function: {xx}")) %>% message
3031

3132
if (getOption("surveytable.raw")) {
@@ -60,19 +61,6 @@ show_opts = function() {
6061
assert_that(is.count(max_levels))
6162
message(paste0("* Maximum number of levels is: ", max_levels))
6263

63-
csv = getOption("surveytable.csv")
64-
assert_that(is.string(csv)
65-
, msg = "CSV file name must be a character string.")
66-
if (nzchar(csv)) {
67-
message(paste0("* Sending CSV output to: ", csv))
68-
if (file.exists(csv)) {
69-
message("* (File already exists. Output will be appended to the end of the file.)")
70-
}
71-
message("* To turn off CSV output: set_opts(csv = '')")
72-
} else {
73-
message("* CSV output has been turned off.")
74-
}
75-
7664
.check_options()
7765
invisible(NULL)
7866
}

R/tab.R

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@
3434
#' @param p_adjust adjust p-values for multiple comparisons?
3535
#' @param drop_na drop missing values (`NA`)? Categorical or logical variables only.
3636
#' @param max_levels a categorical variable can have at most this many levels. Used to avoid printing huge tables.
37-
#' @param csv name of a CSV file
3837
#'
3938
#' @return A list of tables or a single table.
4039
#' @family tables
@@ -54,7 +53,6 @@ tab = function(...
5453
, test = FALSE, alpha = 0.05, p_adjust = FALSE
5554
, drop_na = getOption("surveytable.drop_na")
5655
, max_levels = getOption("surveytable.max_levels")
57-
, csv = getOption("surveytable.csv")
5856
) {
5957
ret = list()
6058
if (...length() > 0) {
@@ -74,20 +72,17 @@ tab = function(...
7472
ret[[vr]] = .tab_factor(design = design
7573
, vr = vr
7674
, drop_na = drop_na
77-
, max_levels = max_levels
78-
, csv = csv)
75+
, max_levels = max_levels)
7976
if (test) {
8077
ret[[paste0(vr, " - test")]] = .test_factor(design = design
8178
, vr = vr
8279
, drop_na = drop_na
8380
, alpha = alpha
84-
, p_adjust = p_adjust
85-
, csv = csv)
81+
, p_adjust = p_adjust)
8682
}
8783
} else if (is.numeric(design$variables[,vr])) {
8884
ret[[vr]] = .tab_numeric(design = design
89-
, vr = vr
90-
, csv = csv)
85+
, vr = vr)
9186
} else {
9287
warning(glue("{vr}: must be logical, categorical (factor or character),",
9388
" or numeric. Is {o2s(design$variables[,vr])}"))
@@ -99,7 +94,7 @@ tab = function(...
9994
if (length(ret) == 1L) ret[[1]] else ret
10095
}
10196

102-
.tab_factor = function(design, vr, drop_na, max_levels, csv) {
97+
.tab_factor = function(design, vr, drop_na, max_levels) {
10398
nm = names(design$variables)
10499
assert_that(vr %in% nm, msg = paste("Variable", vr, "not in the data."))
105100

@@ -143,7 +138,7 @@ tab = function(...
143138
}
144139
attr(mp, "num") = 2:6
145140
attr(mp, "title") = .getvarname(design, vr)
146-
return(.write_out(mp, csv = csv))
141+
return(.finalize_tab(mp))
147142
} else if (nlv > max_levels) {
148143
# don't use assert_that
149144
# if multiple tables are being produced, want to go to the next table
@@ -277,7 +272,7 @@ tab = function(...
277272
mp %<>% .add_flags( list(pro, pco, ppo) )
278273
}
279274

280-
.write_out(mp, csv = csv)
275+
.finalize_tab(mp)
281276
}
282277

283278
.add_flags = function(df1, lfo) {

R/tab_cross.R

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
#' @rdname tab_subset
22
#' @export
3-
tab_cross = function(vr, vrby
4-
, max_levels = getOption("surveytable.max_levels")
5-
, csv = getOption("surveytable.csv")
6-
) {
3+
tab_cross = function(vr, vrby, max_levels = getOption("surveytable.max_levels")
4+
) {
75
design = .load_survey()
86

97
# Ensure unique name
@@ -18,8 +16,7 @@ tab_cross = function(vr, vrby
1816
, .getvarname(design, vrby), ")")
1917
ret = .tab_factor(design = design, vr = newvr
2018
, drop_na = FALSE
21-
, max_levels = max_levels
22-
, csv = csv)
19+
, max_levels = max_levels)
2320

2421
design$variables[,newvr] = NULL
2522
env$survey = design

R/tab_rate.R

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
#' @param per calculate rate per this many items in the population
1111
#' @param drop_na drop missing values (`NA`)?
1212
#' @param max_levels a categorical variable can have at most this many levels. Used to avoid printing huge tables.
13-
#' @param csv name of a CSV file
1413
#'
1514
#' @return A list of tables or a single table.
1615
#' @family tables
@@ -27,7 +26,6 @@ tab_rate = function(vr, pop
2726
, per = getOption("surveytable.rate_per")
2827
, drop_na = getOption("surveytable.drop_na")
2928
, max_levels = getOption("surveytable.max_levels")
30-
, csv = getOption("surveytable.csv")
3129
) {
3230

3331
assert_that(is.data.frame(pop) || is.number(pop)
@@ -61,8 +59,7 @@ tab_rate = function(vr, pop
6159
tfo = .tab_factor(design = design
6260
, vr = vr
6361
, drop_na = drop_na
64-
, max_levels = max_levels
65-
, csv = "")
62+
, max_levels = max_levels)
6663

6764
if (pop_df) {
6865
pop$Population = pop$Population / per
@@ -95,5 +92,5 @@ tab_rate = function(vr, pop
9592
attr(m1, "num") = 2:6
9693
attr(m1, "footer") = attr(tfo, "footer")
9794

98-
.write_out(m1, csv = csv)
95+
.finalize_tab(m1)
9996
}

0 commit comments

Comments
 (0)