subtable | R Documentation |
subtable
yields a subtable of a table tbl
by filtering or extracting a subset of table's
dimensions and levels.
subtable(tbl, in_list = dimnames(tbl), out_list = NULL, quiet = FALSE)
tbl |
An original table to be reduced (as |
in_list |
A list specifying the subset of |
out_list |
A list specifying the subset of |
quiet |
Boolean: Hide feedback messages?
Default: |
subtable
provides a filter/slice function for tables, by specifying
a positive subset (i.e., dimensions and levels to include) as in_list
or
a negative subset (i.e., dimensions and levels to exclude) as out_list
(both as lists that specify dimension and level names, in tag and value format).
subtable
assumes that dimnames(tbl)
exist,
but is flexible in allowing in_list
and out_list
to use both names or numeric indices for subsetting table levels.
As a key constraint, the subset of dimensions specified by
in_list
and out_list
must still contain all dimensions
(as excluding an entire dimension would leave no elements of a table)
and yield a list with elements in the same order as dimnames(tbl)
(to allow using do.call
on what = "[", args
to index/subset the array of tbl).
A table.
Based on the subtable
function by Norman Matloff,
The Art of R Programming (2011, pp. 131-134).
ctable
for creating a contingency table;
sublist
for extracting subsets of a list;
table
and array
for the underlying data structures.
Other array functions:
add_dimnames()
,
ctable()
,
expand_freq_table()
,
flatten_array()
t <- datasets::Titanic
# Trivial case:
subtable(t, in_list = dimnames(t)) # same as t
# (a) Using level names:
subtable(t, in_list = list(Class = c("1st", "2nd", "3rd"),
Sex = "Female", Age = "Adult",
Survived = c("Yes")))
# Alternatives ways of obtaining same result:
subtable(Titanic, out_list = list(Class = c("Crew"),
Sex = "Male", Age = "Child",
Survived = c("No")))
subtable(Titanic, in_list = list(Class = c("1st", "2nd", "3rd"),
Sex = "Female", Age = c("Adult", "Child"),
Survived = c("Yes", "No")),
out_list = list(Age = "Child", Survived = c("No")))
# (b) Using dim names and level numbers:
subtable(t, in_list = list(Class = 1:3, Sex = 2, Age = 2, Survived = 2))
# (c) Using only level numbers (note messages):
subtable(t, in_list = list(1:3, 2, 2, 2))
# (d) Using a mix of level names and numbers (note messages):
subtable(t, in_list = list(1:3, "Female", 2, "Yes"))
# (e) Note: Different length of sub_dims than dimnamesI(tbl) yield ERRORs:
# subtable(t, in_list = list(1:3, "Female", 2, 2, 99))
# Any tbl dimensions (names/levels) not changed by in_list/out_list are included in full:
subtable(t, in_list = list(1:3, "Female", Survived = 2)) # both Age levels included
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.