% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/wtable.R, R/wmean.R, R/wmedian.R, R/wmode.R,
%   R/wvar.R, R/wsd.R, R/wquantile.R, R/wIQR.R, R/wfivenum.R, R/wstandardize.R,
%   R/wsummary.R, R/wmeasures.R
\name{weighted}
\alias{weighted}
\alias{wtable}
\alias{wmean}
\alias{wmedian}
\alias{wmode}
\alias{wvar}
\alias{wsd}
\alias{wquantile}
\alias{wIQR}
\alias{wfivenum}
\alias{wstandardize}
\alias{wsummary}
\alias{wmeasures}
\title{Compute weighted summaries for declared objects}
\usage{
wtable(
  x,
  y = NULL,
  wt = NULL,
  values = TRUE,
  valid = TRUE,
  observed = TRUE,
  vlabel = FALSE
)

wmean(x, wt = NULL, trim = 0, na.rm = TRUE)

wmedian(x, wt = NULL, na.rm = TRUE, ...)

wmode(x, wt = NULL)

wvar(x, wt = NULL, method = NULL, na.rm = TRUE)

wsd(x, wt = NULL, method = NULL, na.rm = TRUE)

wquantile(x, wt = NULL, probs = seq(0, 1, 0.25), na.rm = TRUE, ...)

wIQR(x, wt = NULL, na.rm = FALSE, ...)

wfivenum(x, wt = NULL, na.rm = FALSE)

wstandardize(x, wt = NULL, na.rm = TRUE)

wsummary(x, wt = NULL, ...)

wmeasures(
  x,
  what = c("n", "mode", "mean", "median", "range", "var", "sd"),
  wt = NULL,
  na.rm = TRUE,
  ...
)
}
\arguments{
\item{x}{A numeric vector for summaries, or declared / factor for frequency
tables}

\item{y}{An optional variable, to create crosstabs; must have the same length
as x}

\item{wt}{A numeric vector of frequency weights}

\item{values}{Logical, print the values in the table rows}

\item{valid}{Logical, print separate percent distribution for valid values,
if any missing values are present; for cross tables, use valid values only}

\item{observed}{Logical, print the observed categories only}

\item{vlabel}{Logical, print the variable label, if existing}

\item{trim}{A fraction (0 to 0.5) of observations to be trimmed from each end
of x before the mean is computed. Values of trim outside that range are
taken as the nearest endpoint.}

\item{na.rm}{Logical, should the empty missing values be removed?}

\item{...}{Further arguments passed to or from other methods.}

\item{method}{Character, specifying how the result is scaled, see 'Details'
below.}

\item{probs}{Numeric vector of probabilities with values in [0,1]}

\item{what}{A character vector or a named list of functions, identifying
what to compute. Available character values are \code{"n"}, \code{"NA"}, \code{"mode"},
\code{"mean"}, \code{"median"}, \code{"range"}, \code{"var"}, \code{"sd"}, \code{"iqr"}, \code{"min"}, and
\code{"max"}.}
}
\value{
A vector of (weighted) values.
}
\description{
Functions to compute weighted tables or summaries, based on a vector of
frequency weights. These are reimplementations of various existing functions,
adapted to objects of class \code{"declared"} (see Details below)
}
\details{
Weighted summaries

A frequency table is usually performed for a categorical variable, displaying
the frequencies of the respective categories. Note that general variables
containing text are not necessarily factors, despite having a small number of
characters.

A general table of frequencies, using the base function \code{table()}, ignores
the defined missing values (which are all stored as NAs). The
reimplementation of this function in \code{wtable()} takes care of this detail,
and presents frequencies for each separately defined missing values. Similar
reimplementations for the other functions have the same underlying objective.

It is also possible to perform a frequency table for numerical variables, if
the number of values is limited (an arbitrary and debatable upper limit of 15
is used). An example of such variable can be the number of children, where
each value can be interpreted as a class, containing a single value (for
instance 0 meaning the category of people with no children).

Objects of class \code{declared} are not pure categorical variables (R factors)
but they are nevertheless interpreted as if they were factors, to allow
producing frequency tables. Given the high similarity with package
\strong{\code{haven}}, objects of class \code{haven_labelled_spss} are automatically
coerced to objects of class \code{declared} and treated accordingly.

The argument \code{values} makes sense only when the input is of family class
\code{declared}, otherwise for regular (base R) factors the values are
just a sequence of numbers.

The later introduced argument \code{observed} is useful in situations when a
variable has a very large number of potential values, and a smaller subset of
actually observed ones. As an example, the variable \dQuote{Occupation} has
hundreds of possible values in the ISCO08 codelist, and not all of them might
be actually observed. When activated, this argument restricts the printed
frequency table to the subset of observed values only.

The argument \code{wt} refers only to frequency weights. Users should be
aware of the differences between frequency weights, analytic weights,
probability weights, design weights, post-stratification weights etc. For
purposes of inferential testing, Thomas Lumley's package \strong{\code{survey}}
should be employed.

If no frequency weights are provided, the result is identical to the
corresponding base functions.

For all functions, the argument \code{na.rm} refers to the empty missing values
and its default is set to TRUE. The declared missing values are automatically
eliminated from the summary statistics, even if this argument is deactivated.

The function \code{wmode()} returns the weighted mode of a variable. Unlike the
other functions where the prefix \code{w} signals a weighted version of the
base function with the same name, this has nothing to do with the base
function \code{mode()} which refers to the storage mode or type of an R object.

For \code{wvar()} and \code{wsd()}, the argument \code{method} can be one of \code{"unbiased"}
or \code{"ML"}. The former produces an unbiased estimate using Bessel's
correction, while the latter produces the maximum likelihood estimate for a
Gaussian distribution.

The function \code{wquantile()} extensively borrowed ideas from packages
\strong{\code{stats}} and \strong{\code{Hmisc}}, to ensure a constant interpolation that would
produce the same quantiles if no weights are provided or if all weights are
equal to 1.

Other arguments can be passed to the stats function \code{quantile()} via the
three dots \code{...} argument, and their extensive explanation is found in the
corresponding stats function's help page.

For \code{wmeasures()}, the \code{"n"} measure counts valid values, while \code{"NA"} counts
all missing values, both declared and empty.

When \code{wmeasures()} is evaluated in the context of a data frame, such as with
\code{admisc::using()}, \code{.} can be used as a placeholder for all variables in the
current dataset.
}
\examples{
set.seed(215)

# a pure categorical variable
x <- factor(sample(letters[1:5], 215, replace = TRUE))
wtable(x)


# simulate number of children
x <- sample(0:4, 215, replace = TRUE)
wtable(x)

# simulate a Likert type response scale from 1 to 7
values <- sample(c(1:7, -91), 215, replace = TRUE)
x <- declared(values, labels = c("Good" = 1, "Bad" = 7))
wtable(x)


# Defining missing values
missing_values(x) <- -91
wtable(x)


# Defined missing values with labels
values <- sample(c(1:7, -91, NA), 215, replace = TRUE)
x <- declared(
    values,
    labels = c("Good" = 1, "Bad" = 7, "Don't know" = -91),
    na_values = -91
)

wtable(x)

# Including the values in the table of frequencies
wtable(x, values = TRUE)


# An example involving multiple variables
DF <- data.frame(
    Area = declared(
        sample(1:2, 215, replace = TRUE, prob = c(0.45, 0.55)),
        labels = c(Rural = 1, Urban = 2)
    ),
    Gender = declared(
        sample(1:2, 215, replace = TRUE, prob = c(0.55, 0.45)),
        labels = c(Males = 1, Females = 2)
    ),
    Age = sample(18:90, 215, replace = TRUE),
    Children = sample(0:5, 215, replace = TRUE)
)

wtable(DF$Gender)

wsd(DF$Age)

wmeasures(DF[c("Age", "Children")], what = c("n", "mean", "sd"))


# Weighting: observed proportions
op <- proportions(with(DF, table(Gender, Area)))

# Theoretical proportions: 53\% Rural, and 50.2\% Females
tp <- rep(c(0.53, 0.47), each = 2) * rep(c(0.498, 0.502), 2)

# Corrections by strata
fweights <- tp / op

DF$fweight <- fweights[match(10 * DF$Area + DF$Gender, c(11, 12, 21, 22))]

with(DF, wtable(Gender, wt = fweight))

with(DF, wmean(Age, wt = fweight))

with(DF, wquantile(Age, wt = fweight))
}
\author{
Adrian Dusa
}
