% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/retain.R
\name{retain}
\alias{retain}
\alias{running_number}
\alias{mark_case}
\alias{retain_value}
\alias{retain_stat}
\alias{retain_variables}
\title{Different Facets of Retain}
\usage{
running_number(data_frame, by = NULL, sort = FALSE, group_nr = FALSE)

mark_case(data_frame, by = NULL, first = TRUE)

retain_value(data_frame, values, by = NULL)

retain_stat(data_frame, values, by = NULL, statistics = "sum")

retain_variables(data_frame, ..., order_last = FALSE)
}
\arguments{
\item{data_frame}{The data frame in which to compute retained variables.}

\item{by}{By group in which to compute the retained variable.}

\item{first}{\code{\link[=mark_case]{mark_case()}}: If TRUE marks the first case within a group, otherwise
the last case.}

\item{values}{One or multiple variables of which a value should be retained.}

\item{statistics}{Available functions:
\itemize{
\item "sum"       -> Weighted and unweighted sum
\item "sum_wgt"   -> Sum of all weights
\item "freq"      -> Unweighted frequency
\item "freq_g0"   -> Unweighted frequency of all values greater than zero
\item "pct_group" -> Weighted and unweighted percentages within the respective group
\item "pct_total" -> Weighted and unweighted percentages compared to the grand total
\item "mean"      -> Weighted and unweighted mean
\item "median"    -> Weighted and unweighted median
\item "mode"      -> Weighted and unweighted mode
\item "min"       -> Minimum
\item "max"       -> Maximum
\item "sd"        -> Weighted and unweighted standard deviation
\item "variance"  -> Weighted and unweighted standard variance
\item "first"     -> First value
\item "last"      -> Last value
\item "pn"        -> Weighted and unweighted percentiles (any p1, p2, p3, ... possible)
Uses the SAS default way of calculating percentiles, which is Type 2 described in \code{\link[=quantile]{quantile()}}.
\item "missing"   -> Missings generated by the value variables
}}

\item{...}{\code{\link[=retain_variables]{retain_variables()}}: Put in single variable names or variable ranges
(var_name1:var_name10) which should be ordered to the front or back of the data frame.
It is also possible to provide none existent variable names which will then be added
to the data frame.}

\item{retain_variables}{\code{\link[=retain_variables]{retain_variables()}}: FALSE by default. If TRUE puts the
variables at the end of the data frame instead of the beginning.}
}
\value{
\code{\link[=running_number]{running_number()}}: Returns a vector containing a running number.

\code{\link[=mark_case]{mark_case()}}: Returns a vector containing a the marking for first or last cases.

\code{\link[=retain_value]{retain_value()}}: Returns a vector containing a retained value.

\code{\link[=retain_stat]{retain_stat()}}: Returns a vector containing a retained sum.

\code{\link[=retain_variables]{retain_variables()}}: Return the data frame with reordered variables.
}
\description{
These retain functions all have one thing in common: transferring a value from one case
to the next. What they make out of this functionality can be quiet different. Therefor
there is a function for each different use case.

\code{\link[=running_number]{running_number()}} computes running numbers in a data frame. Without specifying
a by variable results in the row number. With by variable computes the running
number within each group of expressions.

\code{\link[=mark_case]{mark_case()}} sets a flag for the first or last case within the provided by group.

\code{\link[=retain_value]{retain_value()}} retains the first value for all cases of the same group and saves
it into a new variable.

\code{\link[=retain_stat]{retain_stat()}} retains the chosen statistic for all cases of the same group and saves
it into a new variable.

\code{\link[=retain_variables]{retain_variables()}} orders the provided variables to the front or back of the
data frame. If a variable is not part of the data frame it will be added with
all NA values at the desired position.
}
\details{
The functions listed here are based on the 'SAS' function retain. On a very basic level retain
can do two things, depending on the position in the 'SAS' code: It can either sort variables
column wise or it can - since it works row wise - remember a value from one row to the next.
The functions here concentrate on the second part.

Remembering a value from a previous observation offers multiple use cases. E.g. always adding
+1 to the previous case creates a running number. Or if an observation knows the value of the
previous one, it can check whether it is of the same value or another, e.g. to mark first or last
cases within a group.

In it's simplest form it can remember a value from the first observation and transfer it to all
other observations.

All of these functions work on the whole data frame as well as on groups, e.g. to transfer
a value from the first person in a household to all other persons of the same household.
}
\examples{
# Example data frame
my_data <- dummy_data(1000)

# Get row numbers
my_data[["run_nr"]] <- my_data |> running_number()

# Running number per variable expression
my_data[["run_nr_by"]] <- my_data |> running_number(by = year)

# Running number within a group of variables which need to be sorted beforehand
my_data[["run_nr_by_sort"]] <- my_data |>
    running_number(by   = c(sex, education, income_class),
                   sort = TRUE)

# Running number within a group of variables which need to be sorted beforehand
my_data[["run_group"]] <- my_data |>
    running_number(by       = c(sex, education, income_class),
                   sort     = TRUE,
                   group_nr = TRUE)

# Mark first and last cases
my_data[["first"]] <- my_data |> mark_case(by = household_id)
my_data[["last"]]  <- my_data |> mark_case(by    = household_id,
                                           first = FALSE)

# Retain first value without grouping
my_data[["first_weight"]] <- my_data |> retain_value(value = weight)

# Retain first value inside a group for multiple variables
my_data[, c("household_weight", "household_icome")] <- my_data |>
    retain_value(values = c(weight, income),
                 by     = c(state, household_id))

# Retain sum without grouping
my_data[["total_sum"]] <- my_data |> retain_stat(values = weight)

# Retain sum inside a group for multiple variables
my_data[, c("weight_sum", "income_sum")] <- my_data |>
    retain_stat(values = c(weight, income),
                by     = c(year, state, household_id))

# Retain different statistics
my_data[, c("income_freq", "income_max")] <- my_data |>
    retain_stat(values     = income,
                by         = c(year, state, household_id),
                statistics = c("freq", "max"))

# Retain columns inside data frame, which orders them to the front
my_data <- my_data |> retain_variables(age, sex, income)

# Retain columns inside data frame, but order them to the end.
# Variable ranges can also be used.
my_data <- my_data |> retain_variables(age:income, order_last = TRUE)

# Retain columns inside data frame and add new variables with all NA values
my_data <- my_data |> retain_variables(age, sex, income, status1:status5)

# You can also use the colon as a placeholder for any text
start1   <- my_data |> retain_variables("s:")   # Variable names start with "s"
end1     <- my_data |> retain_variables(":id")  # Variable names end with "id"
contain1 <- my_data |> retain_variables(":on:") # Variable names which contain "on"

}
\keyword{internal}
