File: data_tabulate.Rd

package info (click to toggle)
r-cran-datawizard 1.0.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,300 kB
  • sloc: sh: 13; makefile: 2
file content (260 lines) | stat: -rw-r--r-- 10,162 bytes parent folder | download
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/data_tabulate.R
\name{data_tabulate}
\alias{data_tabulate}
\alias{data_tabulate.default}
\alias{data_tabulate.data.frame}
\alias{as.data.frame.datawizard_tables}
\title{Create frequency and crosstables of variables}
\usage{
data_tabulate(x, ...)

\method{data_tabulate}{default}(
  x,
  by = NULL,
  drop_levels = FALSE,
  weights = NULL,
  remove_na = FALSE,
  proportions = NULL,
  name = NULL,
  verbose = TRUE,
  ...
)

\method{data_tabulate}{data.frame}(
  x,
  select = NULL,
  exclude = NULL,
  ignore_case = FALSE,
  regex = FALSE,
  by = NULL,
  drop_levels = FALSE,
  weights = NULL,
  remove_na = FALSE,
  proportions = NULL,
  collapse = FALSE,
  verbose = TRUE,
  ...
)

\method{as.data.frame}{datawizard_tables}(
  x,
  row.names = NULL,
  optional = FALSE,
  ...,
  stringsAsFactors = FALSE,
  add_total = FALSE
)
}
\arguments{
\item{x}{A (grouped) data frame, a vector or factor.}

\item{...}{not used.}

\item{by}{Optional vector or factor. If supplied, a crosstable is created.
If \code{x} is a data frame, \code{by} can also be a character string indicating the
name of a variable in \code{x}.}

\item{drop_levels}{Logical, if \code{FALSE}, factor levels that do not occur in
the data are included in the table (with frequency of zero), else unused
factor levels are dropped from the frequency table.}

\item{weights}{Optional numeric vector of weights. Must be of the same length
as \code{x}. If \code{weights} is supplied, weighted frequencies are calculated.}

\item{remove_na}{Logical, if \code{FALSE}, missing values are included in the
frequency or crosstable, else missing values are omitted.}

\item{proportions}{Optional character string, indicating the type of
percentages to be calculated. Only applies to crosstables, i.e. when \code{by} is
not \code{NULL}. Can be \code{"row"} (row percentages), \code{"column"} (column percentages)
or \code{"full"} (to calculate relative frequencies for the full table).}

\item{name}{Optional character string, which includes the name that is used
for printing.}

\item{verbose}{Toggle warnings.}

\item{select}{Variables that will be included when performing the required
tasks. Can be either
\itemize{
\item a variable specified as a literal variable name (e.g., \code{column_name}),
\item a string with the variable name (e.g., \code{"column_name"}), a character
vector of variable names (e.g., \code{c("col1", "col2", "col3")}), or a
character vector of variable names including ranges specified via \code{:}
(e.g., \code{c("col1:col3", "col5")}),
\item for some functions, like \code{data_select()} or \code{data_rename()}, \code{select} can
be a named character vector. In this case, the names are used to rename
the columns in the output data frame. See 'Details' in the related
functions to see where this option applies.
\item a formula with variable names (e.g., \code{~column_1 + column_2}),
\item a vector of positive integers, giving the positions counting from the left
(e.g. \code{1} or \code{c(1, 3, 5)}),
\item a vector of negative integers, giving the positions counting from the
right (e.g., \code{-1} or \code{-1:-3}),
\item one of the following select-helpers: \code{starts_with()}, \code{ends_with()},
\code{contains()}, a range using \code{:}, or \code{regex()}. \code{starts_with()},
\code{ends_with()}, and  \code{contains()} accept several patterns, e.g
\code{starts_with("Sep", "Petal")}. \code{regex()} can be used to define regular
expression patterns.
\item a function testing for logical conditions, e.g. \code{is.numeric()} (or
\code{is.numeric}), or any user-defined function that selects the variables
for which the function returns \code{TRUE} (like: \code{foo <- function(x) mean(x) > 3}),
\item ranges specified via literal variable names, select-helpers (except
\code{regex()}) and (user-defined) functions can be negated, i.e. return
non-matching elements, when prefixed with a \code{-}, e.g. \code{-ends_with()},
\code{-is.numeric} or \code{-(Sepal.Width:Petal.Length)}. \strong{Note:} Negation means
that matches are \emph{excluded}, and thus, the \code{exclude} argument can be
used alternatively. For instance, \code{select=-ends_with("Length")} (with
\code{-}) is equivalent to \code{exclude=ends_with("Length")} (no \code{-}). In case
negation should not work as expected, use the \code{exclude} argument instead.
}

If \code{NULL}, selects all columns. Patterns that found no matches are silently
ignored, e.g. \code{extract_column_names(iris, select = c("Species", "Test"))}
will just return \code{"Species"}.}

\item{exclude}{See \code{select}, however, column names matched by the pattern
from \code{exclude} will be excluded instead of selected. If \code{NULL} (the default),
excludes no columns.}

\item{ignore_case}{Logical, if \code{TRUE} and when one of the select-helpers or
a regular expression is used in \code{select}, ignores lower/upper case in the
search pattern when matching against variable names.}

\item{regex}{Logical, if \code{TRUE}, the search pattern from \code{select} will be
treated as regular expression. When \code{regex = TRUE}, select \emph{must} be a
character string (or a variable containing a character string) and is not
allowed to be one of the supported select-helpers or a character vector
of length > 1. \code{regex = TRUE} is comparable to using one of the two
select-helpers, \code{select = contains()} or \code{select = regex()}, however,
since the select-helpers may not work when called from inside other
functions (see 'Details'), this argument may be used as workaround.}

\item{collapse}{Logical, if \code{TRUE} collapses multiple tables into one larger
table for printing. This affects only printing, not the returned object.}

\item{row.names}{\code{NULL} or a character vector giving the row
    names for the data frame.  Missing values are not allowed.}

\item{optional}{logical. If \code{TRUE}, setting row names and
    converting column names (to syntactic names: see
    \code{\link[base]{make.names}}) is optional.  Note that all of \R's
    \pkg{base} package \code{as.data.frame()} methods use
    \code{optional} only for column names treatment, basically with the
    meaning of \code{\link[base]{data.frame}(*, check.names = !optional)}.
    See also the \code{make.names} argument of the \code{matrix} method.}

\item{stringsAsFactors}{logical: should the character vector be converted
    to a factor?}

\item{add_total}{For crosstables (i.e. when \code{by} is not \code{NULL}), a row and
column with the total N values are added to the data frame. \code{add_total} has
no effect in \code{as.data.frame()} for simple frequency tables.}
}
\value{
A data frame, or a list of data frames, with one frequency table
as data frame per variable.
}
\description{
This function creates frequency or crosstables of variables,
including the number of levels/values as well as the distribution of raw,
valid and cumulative percentages. For crosstables, row, column  and cell
percentages can be calculated.
}
\details{
There is an \code{as.data.frame()} method, to return the frequency tables as a
data frame. The structure of the returned object is a nested data frame,
where the first column contains name of the variable for which frequencies
were calculated, and the second column is a list column that contains the
frequency tables as data frame. See 'Examples'.
}
\note{
There are \code{print_html()} and \code{print_md()} methods available for printing
frequency or crosstables in HTML and markdown format, e.g.
\code{print_html(data_tabulate(x))}. The \code{print()} method for text outputs passes
arguments in \code{...} to \code{\link[insight:export_table]{insight::export_table()}}.
}
\section{Crosstables}{

If \code{by} is supplied, a crosstable is created. The crosstable includes \verb{<NA>}
(missing) values by default. The first column indicates values of \code{x}, the
first row indicates values of \code{by} (including missing values). The last row
and column contain the total frequencies for each row and column, respectively.
Setting \code{remove_na = FALSE} will omit missing values from the crosstable.
Setting \code{proportions} to \code{"row"} or \code{"column"} will add row or column
percentages. Setting \code{proportions} to \code{"full"} will add relative frequencies
for the full table.
}

\examples{
\dontshow{if (requireNamespace("poorman")) (if (getRversion() >= "3.4") withAutoprint else force)(\{ # examplesIf}
# frequency tables -------
# ------------------------
data(efc)

# vector/factor
data_tabulate(efc$c172code)

# drop missing values
data_tabulate(efc$c172code, remove_na = TRUE)

# data frame
data_tabulate(efc, c("e42dep", "c172code"))

# grouped data frame
suppressPackageStartupMessages(library(poorman, quietly = TRUE))
efc \%>\%
  group_by(c172code) \%>\%
  data_tabulate("e16sex")

# collapse tables
efc \%>\%
  group_by(c172code) \%>\%
  data_tabulate("e16sex", collapse = TRUE)

# for larger N's (> 100000), a big mark is automatically added
set.seed(123)
x <- sample(1:3, 1e6, TRUE)
data_tabulate(x, name = "Large Number")

# to remove the big mark, use "print(..., big_mark = "")"
print(data_tabulate(x), big_mark = "")

# weighted frequencies
set.seed(123)
efc$weights <- abs(rnorm(n = nrow(efc), mean = 1, sd = 0.5))
data_tabulate(efc$e42dep, weights = efc$weights)

# crosstables ------
# ------------------

# add some missing values
set.seed(123)
efc$e16sex[sample.int(nrow(efc), 5)] <- NA

data_tabulate(efc, "c172code", by = "e16sex")

# add row and column percentages
data_tabulate(efc, "c172code", by = "e16sex", proportions = "row")
data_tabulate(efc, "c172code", by = "e16sex", proportions = "column")

# omit missing values
data_tabulate(
  efc$c172code,
  by = efc$e16sex,
  proportions = "column",
  remove_na = TRUE
)

# round percentages
out <- data_tabulate(efc, "c172code", by = "e16sex", proportions = "column")
print(out, digits = 0)

# coerce to data frames
result <- data_tabulate(efc, "c172code", by = "e16sex")
as.data.frame(result)
as.data.frame(result)$table
as.data.frame(result, add_total = TRUE)$table
\dontshow{\}) # examplesIf}
}