From bd33138d6afa3f24f8c53625c31b043fff9a627a Mon Sep 17 00:00:00 2001 From: "Mattan S. Ben-Shachar" Date: Tue, 8 Aug 2023 11:08:52 +0300 Subject: [PATCH 01/26] init #443 --- NAMESPACE | 1 + R/contrs.R | 83 +++++++++++++++++++++++++++++++++++++++ man/contr.deviation.Rd | 89 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 173 insertions(+) create mode 100644 R/contrs.R create mode 100644 man/contr.deviation.Rd diff --git a/NAMESPACE b/NAMESPACE index 08ec43927..1f8c541f1 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -202,6 +202,7 @@ export(coef_var) export(coerce_to_numeric) export(colnames_to_row) export(column_as_rownames) +export(contr.deviation) export(convert_na_to) export(convert_to_na) export(data_addprefix) diff --git a/R/contrs.R b/R/contrs.R new file mode 100644 index 000000000..f46543042 --- /dev/null +++ b/R/contrs.R @@ -0,0 +1,83 @@ +#' Deviation Contrast Matrix +#' +#' Build a deviation contrast matrix, a type of _effects contrast_ matrix. +#' +#' @inheritParams stats::contr.sum +#' +#' @details +#' In effects coding, unlike dummy coding ([stats::contr.treatment()]), each +#' contrasts sums to 0. In regressions models, this results in an intercept that +#' represents the (unweighted) average of the group means. In ANOVA settings, +#' this also guarantees that lower order effects represent _main_ effects (and +#' not _simple_ or _conditional_ effects, as is the case when using +#' [stats::contr.treatment()], which is `R`'s default). +#' \cr\cr +#' `contr.deviation`, unlike [stats::contr.sum()], also has the added benefit +#' that the factor-related coefficients are interpretable. In fact, they +#' represent the same contrasts as those of [stats::contr.treatment()]: the +#' difference of each level from the base level. +#' +#' @seealso [stats::contr.sum()] +#' +#' @examples +#' \dontrun{ +#' data("mtcars") +#' +#' mtcars$cyl <- factor(mtcars$cyl) +#' +#' c.treatment <- cbind(Intercept = 1, contrasts(mtcars$cyl)) +#' solve(c.treatment) +#' #> 4 6 8 +#' #> Intercept 1 0 0 # Intercept is the mean of the 1st level +#' #> 6 -1 1 0 # Difference between 2nd and 1st level +#' #> 8 -1 0 1 # Difference between 3rd and 1st level +#' +#' contrasts(mtcars$cyl) <- contr.sum +#' c.sum <- cbind(Intercept = 1, contrasts(mtcars$cyl)) +#' solve(c.sum) +#' #> 4 6 8 +#' #> Intercept 0.3333333 0.3333333 0.3333333 # Intercept is the overall mean +#' #> 0.6666667 -0.3333333 -0.3333333 # 2/3 of the different between 2nd/3rd and 1st levels +#' #> -0.3333333 0.6666667 -0.3333333 # 2/3 of the different between 1st/3rd and 2nd levels +#' +#' +#' contrasts(mtcars$cyl) <- contr.deviation +#' c.deviation <- cbind(Intercept = 1, contrasts(mtcars$cyl)) +#' solve(c.deviation) +#' #> 4 6 8 +#' #> Intercept 0.3333333 0.3333333 0.3333333 # Intercept is the overall mean +#' #> 6 -1.0000000 1.0000000 0.0000000 # Difference between 2nd and 1st level +#' #> 8 -1.0000000 0.0000000 1.0000000 # Difference between 3rd and 1st level +#' +#' ## With Interactions ----------------------------------------- +#' mtcars$am <- factor(mtcars$am) +#' contrasts(mtcars$am) <- contr.deviation +#' +#' mtcars <- mtcars[order(mtcars$cyl, mtcars$am),] +#' mm <- unique(model.matrix(~ cyl * am, data = mtcars)) +#' rownames(mm) <- c("cyl4.am0", "cyl4.am1", "cyl6.am0", "cyl6.am1", "cyl8.am0", "cyl8.am1") +#' +#' solve(mm) +#' #> cyl4.am0 cyl4.am1 cyl6.am0 cyl6.am1 cyl8.am0 cyl8.am1 +#' #> (Intercept) 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667 # Overall mean +#' #> cyl6 -0.5000000 -0.5000000 0.5000000 0.5000000 0.0000000 0.0000000 # MAIN effect cyl contrasts - 2nd and 1st diff +#' #> cyl8 -0.5000000 -0.5000000 0.0000000 0.0000000 0.5000000 0.5000000 # MAIN effect cyl contrasts - 3rd and 1st diff +#' #> am1 -0.3333333 0.3333333 -0.3333333 0.3333333 -0.3333333 0.3333333 # MAIN effect for am +#' #> cyl6:am1 1.0000000 -1.0000000 -1.0000000 1.0000000 0.0000000 0.0000000 +#' #> cyl8:am1 1.0000000 -1.0000000 0.0000000 0.0000000 -1.0000000 1.0000000 +#' } +#' +#' @export +contr.deviation <- function(n, base = 1, + contrasts = TRUE, + sparse = FALSE) { + cont <- stats::contr.treatment(n, + base = base, + contrasts = contrasts, + sparse = sparse) + if (contrasts) { + n <- nrow(cont) + cont <- cont - 1 / n + } + cont +} diff --git a/man/contr.deviation.Rd b/man/contr.deviation.Rd new file mode 100644 index 000000000..345a0edd3 --- /dev/null +++ b/man/contr.deviation.Rd @@ -0,0 +1,89 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/contrs.R +\name{contr.deviation} +\alias{contr.deviation} +\title{Deviation Contrast Matrix} +\usage{ +contr.deviation(n, base = 1, contrasts = TRUE, sparse = FALSE) +} +\arguments{ +\item{n}{a vector of levels for a factor, or the number of levels.} + +\item{base}{an integer specifying which group is considered the + baseline group. Ignored if \code{contrasts} is \code{FALSE}.} + +\item{contrasts}{a logical indicating whether contrasts should be + computed.} + +\item{sparse}{logical indicating if the result should be sparse + (of class \code{\link[Matrix:dgCMatrix-class]{dgCMatrix}}), using + package \href{https://CRAN.R-project.org/package=Matrix}{\pkg{Matrix}}.} +} +\description{ +Build a deviation contrast matrix, a type of \emph{effects contrast} matrix. +} +\details{ +In effects coding, unlike dummy coding (\code{\link[stats:contrast]{stats::contr.treatment()}}), each +contrasts sums to 0. In regressions models, this results in an intercept that +represents the (unweighted) average of the group means. In ANOVA settings, +this also guarantees that lower order effects represent \emph{main} effects (and +not \emph{simple} or \emph{conditional} effects, as is the case when using +\code{\link[stats:contrast]{stats::contr.treatment()}}, which is \code{R}'s default). +\cr\cr +\code{contr.deviation}, unlike \code{\link[stats:contrast]{stats::contr.sum()}}, also has the added benefit +that the factor-related coefficients are interpretable. In fact, they +represent the same contrasts as those of \code{\link[stats:contrast]{stats::contr.treatment()}}: the +difference of each level from the base level. +} +\examples{ +\dontrun{ +data("mtcars") + +mtcars$cyl <- factor(mtcars$cyl) + +c.treatment <- cbind(Intercept = 1, contrasts(mtcars$cyl)) +solve(c.treatment) +#> 4 6 8 +#> Intercept 1 0 0 # Intercept is the mean of the 1st level +#> 6 -1 1 0 # Difference between 2nd and 1st level +#> 8 -1 0 1 # Difference between 3rd and 1st level + +contrasts(mtcars$cyl) <- contr.sum +c.sum <- cbind(Intercept = 1, contrasts(mtcars$cyl)) +solve(c.sum) +#> 4 6 8 +#> Intercept 0.3333333 0.3333333 0.3333333 # Intercept is the overall mean +#> 0.6666667 -0.3333333 -0.3333333 # 2/3 of the different between 2nd/3rd and 1st levels +#> -0.3333333 0.6666667 -0.3333333 # 2/3 of the different between 1st/3rd and 2nd levels + + +contrasts(mtcars$cyl) <- contr.deviation +c.deviation <- cbind(Intercept = 1, contrasts(mtcars$cyl)) +solve(c.deviation) +#> 4 6 8 +#> Intercept 0.3333333 0.3333333 0.3333333 # Intercept is the overall mean +#> 6 -1.0000000 1.0000000 0.0000000 # Difference between 2nd and 1st level +#> 8 -1.0000000 0.0000000 1.0000000 # Difference between 3rd and 1st level + +## With Interactions ----------------------------------------- +mtcars$am <- factor(mtcars$am) +contrasts(mtcars$am) <- contr.deviation + +mtcars <- mtcars[order(mtcars$cyl, mtcars$am),] +mm <- unique(model.matrix(~ cyl * am, data = mtcars)) +rownames(mm) <- c("cyl4.am0", "cyl4.am1", "cyl6.am0", "cyl6.am1", "cyl8.am0", "cyl8.am1") + +solve(mm) +#> cyl4.am0 cyl4.am1 cyl6.am0 cyl6.am1 cyl8.am0 cyl8.am1 +#> (Intercept) 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667 # Overall mean +#> cyl6 -0.5000000 -0.5000000 0.5000000 0.5000000 0.0000000 0.0000000 # MAIN effect cyl contrasts - 2nd and 1st diff +#> cyl8 -0.5000000 -0.5000000 0.0000000 0.0000000 0.5000000 0.5000000 # MAIN effect cyl contrasts - 3rd and 1st diff +#> am1 -0.3333333 0.3333333 -0.3333333 0.3333333 -0.3333333 0.3333333 # MAIN effect for am +#> cyl6:am1 1.0000000 -1.0000000 -1.0000000 1.0000000 0.0000000 0.0000000 +#> cyl8:am1 1.0000000 -1.0000000 0.0000000 0.0000000 -1.0000000 1.0000000 +} + +} +\seealso{ +\code{\link[stats:contrast]{stats::contr.sum()}} +} From c6b653d105bdf268428786949ed606baad4c187b Mon Sep 17 00:00:00 2001 From: "Mattan S. Ben-Shachar" Date: Tue, 8 Aug 2023 11:26:26 +0300 Subject: [PATCH 02/26] Update _pkgdown.yaml --- _pkgdown.yaml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/_pkgdown.yaml b/_pkgdown.yaml index 038a405a3..ff3f4ba7f 100644 --- a/_pkgdown.yaml +++ b/_pkgdown.yaml @@ -23,7 +23,8 @@ reference: - data_duplicated - data_unique - - title: Statistical Transformations + - title: Data and Variable Transformations + - subtitle: Statistical Transformations desc: | Functions for transforming variables contents: @@ -51,6 +52,9 @@ reference: - normalize - unstandardize - makepredictcall.dw_transformer + - subtitle: "Others" + contents: + - contr.deviation - title: Data Properties desc: | From e91ec00d097eb839cc9d2600fd32ed23b495637b Mon Sep 17 00:00:00 2001 From: "Mattan S. Ben-Shachar" Date: Tue, 8 Aug 2023 11:36:50 +0300 Subject: [PATCH 03/26] fix note --- R/contrs.R | 39 ++++++++++++++++++------------------ man/contr.deviation.Rd | 39 ++++++++++++++++++------------------ man/describe_distribution.Rd | 13 +++++++++--- 3 files changed, 50 insertions(+), 41 deletions(-) diff --git a/R/contrs.R b/R/contrs.R index f46543042..3cf634b94 100644 --- a/R/contrs.R +++ b/R/contrs.R @@ -28,26 +28,26 @@ #' c.treatment <- cbind(Intercept = 1, contrasts(mtcars$cyl)) #' solve(c.treatment) #' #> 4 6 8 -#' #> Intercept 1 0 0 # Intercept is the mean of the 1st level -#' #> 6 -1 1 0 # Difference between 2nd and 1st level -#' #> 8 -1 0 1 # Difference between 3rd and 1st level +#' #> Intercept 1 0 0 # mean of the 1st level +#' #> 6 -1 1 0 # 2nd level - 1st level +#' #> 8 -1 0 1 # 3rd level - 1st level #' #' contrasts(mtcars$cyl) <- contr.sum #' c.sum <- cbind(Intercept = 1, contrasts(mtcars$cyl)) #' solve(c.sum) -#' #> 4 6 8 -#' #> Intercept 0.3333333 0.3333333 0.3333333 # Intercept is the overall mean -#' #> 0.6666667 -0.3333333 -0.3333333 # 2/3 of the different between 2nd/3rd and 1st levels -#' #> -0.3333333 0.6666667 -0.3333333 # 2/3 of the different between 1st/3rd and 2nd levels +#' #> 4 6 8 +#' #> Intercept 0.333 0.333 0.333 # overall mean +#' #> 0.667 -0.333 -0.333 # 2/3 * ({2nd, 3rd} - 1st) +#' #> -0.333 0.667 -0.333 # 2/3 * ({1st, 3rd} - 2nd) #' #' #' contrasts(mtcars$cyl) <- contr.deviation #' c.deviation <- cbind(Intercept = 1, contrasts(mtcars$cyl)) #' solve(c.deviation) -#' #> 4 6 8 -#' #> Intercept 0.3333333 0.3333333 0.3333333 # Intercept is the overall mean -#' #> 6 -1.0000000 1.0000000 0.0000000 # Difference between 2nd and 1st level -#' #> 8 -1.0000000 0.0000000 1.0000000 # Difference between 3rd and 1st level +#' #> 4 6 8 +#' #> Intercept 0.333 0.333 0.333 # overall mean +#' #> 6 -1.000 1.000 0.000 # 2nd level - 1st level +#' #> 8 -1.000 0.000 1.000 # 3rd level - 1st level #' #' ## With Interactions ----------------------------------------- #' mtcars$am <- factor(mtcars$am) @@ -55,16 +55,17 @@ #' #' mtcars <- mtcars[order(mtcars$cyl, mtcars$am),] #' mm <- unique(model.matrix(~ cyl * am, data = mtcars)) -#' rownames(mm) <- c("cyl4.am0", "cyl4.am1", "cyl6.am0", "cyl6.am1", "cyl8.am0", "cyl8.am1") +#' rownames(mm) <- c("cyl4.am0", "cyl4.am1", "cyl6.am0", +#' "cyl6.am1", "cyl8.am0", "cyl8.am1") #' #' solve(mm) -#' #> cyl4.am0 cyl4.am1 cyl6.am0 cyl6.am1 cyl8.am0 cyl8.am1 -#' #> (Intercept) 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667 # Overall mean -#' #> cyl6 -0.5000000 -0.5000000 0.5000000 0.5000000 0.0000000 0.0000000 # MAIN effect cyl contrasts - 2nd and 1st diff -#' #> cyl8 -0.5000000 -0.5000000 0.0000000 0.0000000 0.5000000 0.5000000 # MAIN effect cyl contrasts - 3rd and 1st diff -#' #> am1 -0.3333333 0.3333333 -0.3333333 0.3333333 -0.3333333 0.3333333 # MAIN effect for am -#' #> cyl6:am1 1.0000000 -1.0000000 -1.0000000 1.0000000 0.0000000 0.0000000 -#' #> cyl8:am1 1.0000000 -1.0000000 0.0000000 0.0000000 -1.0000000 1.0000000 +#' #> cyl4.am0 cyl4.am1 cyl6.am0 cyl6.am1 cyl8.am0 cyl8.am1 +#' #> (Intercept) 0.167 0.167 0.167 0.167 0.167 0.167 # overall mean +#' #> cyl6 -0.500 -0.500 0.500 0.500 0.000 0.000 # cyl MAIN eff: 2nd - 1st +#' #> cyl8 -0.500 -0.500 0.000 0.000 0.500 0.500 # cyl MAIN eff: 2nd - 1st +#' #> am1 -0.333 0.333 -0.333 0.333 -0.333 0.333 # am MAIN eff +#' #> cyl6:am1 1.000 -1.000 -1.000 1.000 0.000 0.000 +#' #> cyl8:am1 1.000 -1.000 0.000 0.000 -1.000 1.000 #' } #' #' @export diff --git a/man/contr.deviation.Rd b/man/contr.deviation.Rd index 345a0edd3..d7a7242f9 100644 --- a/man/contr.deviation.Rd +++ b/man/contr.deviation.Rd @@ -44,26 +44,26 @@ mtcars$cyl <- factor(mtcars$cyl) c.treatment <- cbind(Intercept = 1, contrasts(mtcars$cyl)) solve(c.treatment) #> 4 6 8 -#> Intercept 1 0 0 # Intercept is the mean of the 1st level -#> 6 -1 1 0 # Difference between 2nd and 1st level -#> 8 -1 0 1 # Difference between 3rd and 1st level +#> Intercept 1 0 0 # mean of the 1st level +#> 6 -1 1 0 # 2nd level - 1st level +#> 8 -1 0 1 # 3rd level - 1st level contrasts(mtcars$cyl) <- contr.sum c.sum <- cbind(Intercept = 1, contrasts(mtcars$cyl)) solve(c.sum) -#> 4 6 8 -#> Intercept 0.3333333 0.3333333 0.3333333 # Intercept is the overall mean -#> 0.6666667 -0.3333333 -0.3333333 # 2/3 of the different between 2nd/3rd and 1st levels -#> -0.3333333 0.6666667 -0.3333333 # 2/3 of the different between 1st/3rd and 2nd levels +#> 4 6 8 +#> Intercept 0.333 0.333 0.333 # overall mean +#> 0.667 -0.333 -0.333 # 2/3 * ({2nd, 3rd} - 1st) +#> -0.333 0.667 -0.333 # 2/3 * ({1st, 3rd} - 2nd) contrasts(mtcars$cyl) <- contr.deviation c.deviation <- cbind(Intercept = 1, contrasts(mtcars$cyl)) solve(c.deviation) -#> 4 6 8 -#> Intercept 0.3333333 0.3333333 0.3333333 # Intercept is the overall mean -#> 6 -1.0000000 1.0000000 0.0000000 # Difference between 2nd and 1st level -#> 8 -1.0000000 0.0000000 1.0000000 # Difference between 3rd and 1st level +#> 4 6 8 +#> Intercept 0.333 0.333 0.333 # overall mean +#> 6 -1.000 1.000 0.000 # 2nd level - 1st level +#> 8 -1.000 0.000 1.000 # 3rd level - 1st level ## With Interactions ----------------------------------------- mtcars$am <- factor(mtcars$am) @@ -71,16 +71,17 @@ contrasts(mtcars$am) <- contr.deviation mtcars <- mtcars[order(mtcars$cyl, mtcars$am),] mm <- unique(model.matrix(~ cyl * am, data = mtcars)) -rownames(mm) <- c("cyl4.am0", "cyl4.am1", "cyl6.am0", "cyl6.am1", "cyl8.am0", "cyl8.am1") +rownames(mm) <- c("cyl4.am0", "cyl4.am1", "cyl6.am0", + "cyl6.am1", "cyl8.am0", "cyl8.am1") solve(mm) -#> cyl4.am0 cyl4.am1 cyl6.am0 cyl6.am1 cyl8.am0 cyl8.am1 -#> (Intercept) 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667 0.1666667 # Overall mean -#> cyl6 -0.5000000 -0.5000000 0.5000000 0.5000000 0.0000000 0.0000000 # MAIN effect cyl contrasts - 2nd and 1st diff -#> cyl8 -0.5000000 -0.5000000 0.0000000 0.0000000 0.5000000 0.5000000 # MAIN effect cyl contrasts - 3rd and 1st diff -#> am1 -0.3333333 0.3333333 -0.3333333 0.3333333 -0.3333333 0.3333333 # MAIN effect for am -#> cyl6:am1 1.0000000 -1.0000000 -1.0000000 1.0000000 0.0000000 0.0000000 -#> cyl8:am1 1.0000000 -1.0000000 0.0000000 0.0000000 -1.0000000 1.0000000 +#> cyl4.am0 cyl4.am1 cyl6.am0 cyl6.am1 cyl8.am0 cyl8.am1 +#> (Intercept) 0.167 0.167 0.167 0.167 0.167 0.167 # overall mean +#> cyl6 -0.500 -0.500 0.500 0.500 0.000 0.000 # cyl MAIN eff: 2nd - 1st +#> cyl8 -0.500 -0.500 0.000 0.000 0.500 0.500 # cyl MAIN eff: 2nd - 1st +#> am1 -0.333 0.333 -0.333 0.333 -0.333 0.333 # am MAIN eff +#> cyl6:am1 1.000 -1.000 -1.000 1.000 0.000 0.000 +#> cyl8:am1 1.000 -1.000 0.000 0.000 -1.000 1.000 } } diff --git a/man/describe_distribution.Rd b/man/describe_distribution.Rd index a23069eea..fd229567d 100644 --- a/man/describe_distribution.Rd +++ b/man/describe_distribution.Rd @@ -50,9 +50,14 @@ describe_distribution(x, ...) \item{...}{Additional arguments to be passed to or from methods.} -\item{centrality}{The point-estimates (centrality indices) to compute. Character (vector) or list with one or more of these options: \code{"median"}, \code{"mean"}, \code{"MAP"} or \code{"all"}.} +\item{centrality}{The point-estimates (centrality indices) to compute. Character +(vector) or list with one or more of these options: \code{"median"}, \code{"mean"}, \code{"MAP"} +(see \code{\link[bayestestR:map_estimate]{map_estimate()}}), \code{"trimmed"} (which is just \code{mean(x, trim = threshold)}), +\code{"mode"} or \code{"all"}.} -\item{dispersion}{Logical, if \code{TRUE}, computes indices of dispersion related to the estimate(s) (\code{SD} and \code{MAD} for \code{mean} and \code{median}, respectively).} +\item{dispersion}{Logical, if \code{TRUE}, computes indices of dispersion related +to the estimate(s) (\code{SD} and \code{MAD} for \code{mean} and \code{median}, respectively). +Dispersion is not available for \code{"MAP"} or \code{"mode"} centrality indices.} \item{iqr}{Logical, if \code{TRUE}, the interquartile range is calculated (based on \code{\link[stats:IQR]{stats::IQR()}}, using \code{type = 6}).} @@ -71,7 +76,9 @@ the first centrality index (which is typically the median).} \item{iterations}{The number of bootstrap replicates for computing confidence intervals. Only applies when \code{ci} is not \code{NULL}.} -\item{threshold}{For \code{centrality = "trimmed"} (i.e. trimmed mean), indicates the fraction (0 to 0.5) of observations to be trimmed from each end of the vector before the mean is computed.} +\item{threshold}{For \code{centrality = "trimmed"} (i.e. trimmed mean), indicates +the fraction (0 to 0.5) of observations to be trimmed from each end of the +vector before the mean is computed.} \item{verbose}{Toggle warnings and messages.} From d4f149dfc4b35fbce1991a56411fbae4613c3674 Mon Sep 17 00:00:00 2001 From: "Mattan S. Ben-Shachar" Date: Tue, 8 Aug 2023 14:51:20 +0300 Subject: [PATCH 04/26] tests, version, docs, news --- DESCRIPTION | 2 +- NEWS.md | 4 ++++ R/contrs.R | 7 +++---- man/contr.deviation.Rd | 7 +++---- tests/testthat/test-contr.deviation.R | 8 ++++++++ 5 files changed, 19 insertions(+), 9 deletions(-) create mode 100644 tests/testthat/test-contr.deviation.R diff --git a/DESCRIPTION b/DESCRIPTION index 6a0264ee0..3c71a6343 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Type: Package Package: datawizard Title: Easy Data Wrangling and Statistical Transformations -Version: 0.8.0.4 +Version: 0.8.0.5 Authors@R: c( person("Indrajeet", "Patil", , "patilindrajeet.science@gmail.com", role = "aut", comment = c(ORCID = "0000-0003-1995-6531", Twitter = "@patilindrajeets")), diff --git a/NEWS.md b/NEWS.md index c3aee3b24..0d3d94e3b 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,9 @@ # datawizard (devel) +NEW FUNCTIONS + +* `contr.deviation()` for sum-deviation contrast coding of factors. + CHANGES * `recode_into()` gains an `overwrite` argument to skip overwriting already diff --git a/R/contrs.R b/R/contrs.R index 3cf634b94..6a48842df 100644 --- a/R/contrs.R +++ b/R/contrs.R @@ -23,7 +23,7 @@ #' \dontrun{ #' data("mtcars") #' -#' mtcars$cyl <- factor(mtcars$cyl) +#' mtcars <- data_modify(mtcars, cyl = factor(cyl)) #' #' c.treatment <- cbind(Intercept = 1, contrasts(mtcars$cyl)) #' solve(c.treatment) @@ -50,10 +50,9 @@ #' #> 8 -1.000 0.000 1.000 # 3rd level - 1st level #' #' ## With Interactions ----------------------------------------- -#' mtcars$am <- factor(mtcars$am) -#' contrasts(mtcars$am) <- contr.deviation +#' mtcars <- data_modify(mtcars, am = factor(am)) +#' mtcars <- data_arrange(mtcars, select = c("cyl", "am")) #' -#' mtcars <- mtcars[order(mtcars$cyl, mtcars$am),] #' mm <- unique(model.matrix(~ cyl * am, data = mtcars)) #' rownames(mm) <- c("cyl4.am0", "cyl4.am1", "cyl6.am0", #' "cyl6.am1", "cyl8.am0", "cyl8.am1") diff --git a/man/contr.deviation.Rd b/man/contr.deviation.Rd index d7a7242f9..5a796ef10 100644 --- a/man/contr.deviation.Rd +++ b/man/contr.deviation.Rd @@ -39,7 +39,7 @@ difference of each level from the base level. \dontrun{ data("mtcars") -mtcars$cyl <- factor(mtcars$cyl) +mtcars <- data_modify(mtcars, cyl = factor(cyl)) c.treatment <- cbind(Intercept = 1, contrasts(mtcars$cyl)) solve(c.treatment) @@ -66,10 +66,9 @@ solve(c.deviation) #> 8 -1.000 0.000 1.000 # 3rd level - 1st level ## With Interactions ----------------------------------------- -mtcars$am <- factor(mtcars$am) -contrasts(mtcars$am) <- contr.deviation +mtcars <- data_modify(mtcars, am = factor(am)) +mtcars <- data_arrange(mtcars, select = c("cyl", "am")) -mtcars <- mtcars[order(mtcars$cyl, mtcars$am),] mm <- unique(model.matrix(~ cyl * am, data = mtcars)) rownames(mm) <- c("cyl4.am0", "cyl4.am1", "cyl6.am0", "cyl6.am1", "cyl8.am0", "cyl8.am1") diff --git a/tests/testthat/test-contr.deviation.R b/tests/testthat/test-contr.deviation.R new file mode 100644 index 000000000..55e447277 --- /dev/null +++ b/tests/testthat/test-contr.deviation.R @@ -0,0 +1,8 @@ +test_that("contr.deviation", { + c.treatment <- solve(cbind(Intercept = 1, contr.treatment(3))) + c.sum <- solve(cbind(Intercept = 1, contr.sum(3))) + c.deviation <- solve(cbind(Intercept = 1, contr.deviation(3))) + + expect_equal(c.deviation[1,], c.sum[1,]) + expect_equal(c.deviation[-1,], c.treatment[-1,]) +}) From d3c4fc37e5525782a39baf839acca9222ac3704a Mon Sep 17 00:00:00 2001 From: "Mattan S. Ben-Shachar" Date: Tue, 8 Aug 2023 14:53:33 +0300 Subject: [PATCH 05/26] styler --- R/contrs.R | 13 ++++++++----- tests/testthat/test-contr.deviation.R | 4 ++-- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/R/contrs.R b/R/contrs.R index 6a48842df..179d545bb 100644 --- a/R/contrs.R +++ b/R/contrs.R @@ -54,8 +54,10 @@ #' mtcars <- data_arrange(mtcars, select = c("cyl", "am")) #' #' mm <- unique(model.matrix(~ cyl * am, data = mtcars)) -#' rownames(mm) <- c("cyl4.am0", "cyl4.am1", "cyl6.am0", -#' "cyl6.am1", "cyl8.am0", "cyl8.am1") +#' rownames(mm) <- c( +#' "cyl4.am0", "cyl4.am1", "cyl6.am0", +#' "cyl6.am1", "cyl8.am0", "cyl8.am1" +#' ) #' #' solve(mm) #' #> cyl4.am0 cyl4.am1 cyl6.am0 cyl6.am1 cyl8.am0 cyl8.am1 @@ -72,9 +74,10 @@ contr.deviation <- function(n, base = 1, contrasts = TRUE, sparse = FALSE) { cont <- stats::contr.treatment(n, - base = base, - contrasts = contrasts, - sparse = sparse) + base = base, + contrasts = contrasts, + sparse = sparse + ) if (contrasts) { n <- nrow(cont) cont <- cont - 1 / n diff --git a/tests/testthat/test-contr.deviation.R b/tests/testthat/test-contr.deviation.R index 55e447277..40a61af40 100644 --- a/tests/testthat/test-contr.deviation.R +++ b/tests/testthat/test-contr.deviation.R @@ -3,6 +3,6 @@ test_that("contr.deviation", { c.sum <- solve(cbind(Intercept = 1, contr.sum(3))) c.deviation <- solve(cbind(Intercept = 1, contr.deviation(3))) - expect_equal(c.deviation[1,], c.sum[1,]) - expect_equal(c.deviation[-1,], c.treatment[-1,]) + expect_equal(c.deviation[1, ], c.sum[1, ]) + expect_equal(c.deviation[-1, ], c.treatment[-1, ]) }) From a5669f376c11a815a671660c86bdcdc1106d1202 Mon Sep 17 00:00:00 2001 From: "Mattan S. Ben-Shachar" Date: Tue, 8 Aug 2023 15:06:22 +0300 Subject: [PATCH 06/26] add snapshot tests --- tests/testthat/_snaps/contr.deviation.md | 23 +++++++++++++++++++++++ tests/testthat/test-contr.deviation.R | 19 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 tests/testthat/_snaps/contr.deviation.md diff --git a/tests/testthat/_snaps/contr.deviation.md b/tests/testthat/_snaps/contr.deviation.md new file mode 100644 index 000000000..7b3436578 --- /dev/null +++ b/tests/testthat/_snaps/contr.deviation.md @@ -0,0 +1,23 @@ +# contr.deviation | snapshot + + Code + solve(c.deviation) + Output + 4 6 8 + Intercept 0.3333333 0.3333333 0.3333333 + 6 -1.0000000 1.0000000 0.0000000 + 8 -1.0000000 0.0000000 1.0000000 + +--- + + Code + solve(mm) + Output + cyl4.am0 cyl4.am1 cyl6.am0 cyl6.am1 cyl8.am0 cyl8.am1 + (Intercept) 0.3333333 0.0000000 0.3333333 0.0000000 0.3333333 0.0000000 + cyl6 -1.0000000 0.0000000 1.0000000 0.0000000 0.0000000 0.0000000 + cyl8 -1.0000000 0.0000000 0.0000000 0.0000000 1.0000000 0.0000000 + am1 -0.3333333 0.3333333 -0.3333333 0.3333333 -0.3333333 0.3333333 + cyl6:am1 1.0000000 -1.0000000 -1.0000000 1.0000000 0.0000000 0.0000000 + cyl8:am1 1.0000000 -1.0000000 0.0000000 0.0000000 -1.0000000 1.0000000 + diff --git a/tests/testthat/test-contr.deviation.R b/tests/testthat/test-contr.deviation.R index 40a61af40..2315f9c7a 100644 --- a/tests/testthat/test-contr.deviation.R +++ b/tests/testthat/test-contr.deviation.R @@ -6,3 +6,22 @@ test_that("contr.deviation", { expect_equal(c.deviation[1, ], c.sum[1, ]) expect_equal(c.deviation[-1, ], c.treatment[-1, ]) }) + +test_that("contr.deviation | snapshot", { + # IF THIS TESTS FAILS, UPDATE THE EXAMPLE + + data("mtcars") + mtcars <- data_modify(mtcars, cyl = factor(cyl)) + mtcars <- data_modify(mtcars, am = factor(am)) + mtcars <- data_arrange(mtcars, select = c("cyl", "am")) + + contrasts(mtcars$cyl) <- contr.deviation + c.deviation <- cbind(Intercept = 1, contrasts(mtcars$cyl)) + expect_snapshot(solve(c.deviation)) + + mm <- unique(model.matrix(~ cyl * am, data = mtcars)) + rownames(mm) <- c("cyl4.am0", "cyl4.am1", "cyl6.am0", + "cyl6.am1", "cyl8.am0", "cyl8.am1") + + expect_snapshot(solve(mm)) +}) From 9c9407986b139a8a05a6a60c4c18e7246d511e72 Mon Sep 17 00:00:00 2001 From: "Mattan S. Ben-Shachar" Date: Tue, 8 Aug 2023 16:54:43 +0300 Subject: [PATCH 07/26] skip snapshot test on older R --- tests/testthat/test-contr.deviation.R | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/testthat/test-contr.deviation.R b/tests/testthat/test-contr.deviation.R index 2315f9c7a..164c18837 100644 --- a/tests/testthat/test-contr.deviation.R +++ b/tests/testthat/test-contr.deviation.R @@ -8,6 +8,7 @@ test_that("contr.deviation", { }) test_that("contr.deviation | snapshot", { + skip_if_not_installed("base", "4.3") # IF THIS TESTS FAILS, UPDATE THE EXAMPLE data("mtcars") From d93b9c3cf699a05ae80658d62278b066fea3c455 Mon Sep 17 00:00:00 2001 From: "Brenton M. Wiernik" Date: Tue, 8 Aug 2023 11:22:53 -0400 Subject: [PATCH 08/26] Update description of deviation vs sum coding --- R/contrs.R | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/R/contrs.R b/R/contrs.R index 179d545bb..214259b7a 100644 --- a/R/contrs.R +++ b/R/contrs.R @@ -5,17 +5,29 @@ #' @inheritParams stats::contr.sum #' #' @details -#' In effects coding, unlike dummy coding ([stats::contr.treatment()]), each -#' contrasts sums to 0. In regressions models, this results in an intercept that +#' In effects coding, unlike treatment/dummy coding ([stats::contr.treatment()]), each +#' contrast sums to 0. In regressions models, this results in an intercept that #' represents the (unweighted) average of the group means. In ANOVA settings, #' this also guarantees that lower order effects represent _main_ effects (and -#' not _simple_ or _conditional_ effects, as is the case when using -#' [stats::contr.treatment()], which is `R`'s default). +#' not _simple_ or _conditional_ effects, as is the case when using R's default +#' [stats::contr.treatment()]). #' \cr\cr -#' `contr.deviation`, unlike [stats::contr.sum()], also has the added benefit -#' that the factor-related coefficients are interpretable. In fact, they -#' represent the same contrasts as those of [stats::contr.treatment()]: the -#' difference of each level from the base level. +#' Deviation coding (`contr.deviation`) is a type of effects coding. +#' With deviation coding, the coefficients for factor variables are interpreted +#' as the difference of each factor level from the base level +#' (this is the same interpretation as with treatment/dummy coding). +#' For example, for a factor `group` with levels "Red" and "Blue", with `contr.devation`, +#' the intercept represents the average of the group means for Red and Blue groups, +#' and the coefficient for `groupBlue` represents the difference between Blue and Red +#' group means. +#' \cr\cr +#' Sum coding ([stats::contr.sum()]) is another type of effects coding. +#' With sum coding, the coefficients for factor variables are interpreted +#' as the difference of each factor level from **the grand (across-groups) mean**. +#' For example, for a factor `group` with levels "Red" and "Blue", with `contr.sum`, +#' the intercept represents the average of the group means for Red and Blue groups, +#' and the coefficient for `groupBlue` represents the difference of the Red group mean +#' from the grand mean (the average of Red and Blue group means). #' #' @seealso [stats::contr.sum()] #' From 8d8b8995ec7b66400585c5409c4c11953cbdcbf8 Mon Sep 17 00:00:00 2001 From: "Brenton M. Wiernik" Date: Wed, 9 Aug 2023 17:21:30 -0400 Subject: [PATCH 09/26] Fix typo --- R/contrs.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/contrs.R b/R/contrs.R index 214259b7a..4bf4763a5 100644 --- a/R/contrs.R +++ b/R/contrs.R @@ -26,7 +26,7 @@ #' as the difference of each factor level from **the grand (across-groups) mean**. #' For example, for a factor `group` with levels "Red" and "Blue", with `contr.sum`, #' the intercept represents the average of the group means for Red and Blue groups, -#' and the coefficient for `groupBlue` represents the difference of the Red group mean +#' and the coefficient for `groupBlue` represents the difference of the Blue group mean #' from the grand mean (the average of Red and Blue group means). #' #' @seealso [stats::contr.sum()] From bb249d7c10c27b6e25cf6de7f4fb3f2a747d816b Mon Sep 17 00:00:00 2001 From: "Brenton M. Wiernik" Date: Wed, 9 Aug 2023 18:00:35 -0400 Subject: [PATCH 10/26] Update effects coding examples in docs --- R/contrs.R | 22 ++++++++++----------- man/contr.deviation.Rd | 38 ++++++++++++++++++++++++------------ man/describe_distribution.Rd | 13 +++--------- 3 files changed, 40 insertions(+), 33 deletions(-) diff --git a/R/contrs.R b/R/contrs.R index 4bf4763a5..cb1c69722 100644 --- a/R/contrs.R +++ b/R/contrs.R @@ -15,19 +15,19 @@ #' Deviation coding (`contr.deviation`) is a type of effects coding. #' With deviation coding, the coefficients for factor variables are interpreted #' as the difference of each factor level from the base level -#' (this is the same interpretation as with treatment/dummy coding). -#' For example, for a factor `group` with levels "Red" and "Blue", with `contr.devation`, -#' the intercept represents the average of the group means for Red and Blue groups, -#' and the coefficient for `groupBlue` represents the difference between Blue and Red -#' group means. +#' (this is the same interpretation as with treatment/dummy coding). +#' For example, for a factor `group` with levels "A", "B", and "C", with `contr.devation`, +#' the intercept represents the overall mean (average of the group means for the 3 groups), +#' and the coefficients `groupB` and `groupC` represent the differences between +#' the A group mean and the B and C group means, respectively. #' \cr\cr #' Sum coding ([stats::contr.sum()]) is another type of effects coding. #' With sum coding, the coefficients for factor variables are interpreted #' as the difference of each factor level from **the grand (across-groups) mean**. -#' For example, for a factor `group` with levels "Red" and "Blue", with `contr.sum`, -#' the intercept represents the average of the group means for Red and Blue groups, -#' and the coefficient for `groupBlue` represents the difference of the Blue group mean -#' from the grand mean (the average of Red and Blue group means). +#' For example, for a factor `group` with levels "A", "B", and "C", with `contr.sum`, +#' the intercept represents the overall mean (average of the group means for the 3 groups), +#' and the coefficients `group1` and `group2` represent the differences the +#' **A** and **B** group means from the overall mean, respectively. #' #' @seealso [stats::contr.sum()] #' @@ -49,8 +49,8 @@ #' solve(c.sum) #' #> 4 6 8 #' #> Intercept 0.333 0.333 0.333 # overall mean -#' #> 0.667 -0.333 -0.333 # 2/3 * ({2nd, 3rd} - 1st) -#' #> -0.333 0.667 -0.333 # 2/3 * ({1st, 3rd} - 2nd) +#' #> 0.667 -0.333 -0.333 # deviation of 1st from overall mean +#' #> -0.333 0.667 -0.333 # deviation of 2nd from overall mean #' #' #' contrasts(mtcars$cyl) <- contr.deviation diff --git a/man/contr.deviation.Rd b/man/contr.deviation.Rd index 5a796ef10..f44106111 100644 --- a/man/contr.deviation.Rd +++ b/man/contr.deviation.Rd @@ -23,17 +23,29 @@ contr.deviation(n, base = 1, contrasts = TRUE, sparse = FALSE) Build a deviation contrast matrix, a type of \emph{effects contrast} matrix. } \details{ -In effects coding, unlike dummy coding (\code{\link[stats:contrast]{stats::contr.treatment()}}), each -contrasts sums to 0. In regressions models, this results in an intercept that +In effects coding, unlike treatment/dummy coding (\code{\link[stats:contrast]{stats::contr.treatment()}}), each +contrast sums to 0. In regressions models, this results in an intercept that represents the (unweighted) average of the group means. In ANOVA settings, this also guarantees that lower order effects represent \emph{main} effects (and -not \emph{simple} or \emph{conditional} effects, as is the case when using -\code{\link[stats:contrast]{stats::contr.treatment()}}, which is \code{R}'s default). +not \emph{simple} or \emph{conditional} effects, as is the case when using R's default +\code{\link[stats:contrast]{stats::contr.treatment()}}). \cr\cr -\code{contr.deviation}, unlike \code{\link[stats:contrast]{stats::contr.sum()}}, also has the added benefit -that the factor-related coefficients are interpretable. In fact, they -represent the same contrasts as those of \code{\link[stats:contrast]{stats::contr.treatment()}}: the -difference of each level from the base level. +Deviation coding (\code{contr.deviation}) is a type of effects coding. +With deviation coding, the coefficients for factor variables are interpreted +as the difference of each factor level from the base level +(this is the same interpretation as with treatment/dummy coding). +For example, for a factor \code{group} with levels "A", "B", and "C", with \code{contr.devation}, +the intercept represents the overall mean (average of the group means for the 3 groups), +and the coefficients \code{groupB} and \code{groupC} represent the differences between +the A group mean and the B and C group means, respectively. +\cr\cr +Sum coding (\code{\link[stats:contrast]{stats::contr.sum()}}) is another type of effects coding. +With sum coding, the coefficients for factor variables are interpreted +as the difference of each factor level from \strong{the grand (across-groups) mean}. +For example, for a factor \code{group} with levels "A", "B", and "C", with \code{contr.sum}, +the intercept represents the overall mean (average of the group means for the 3 groups), +and the coefficients \code{group1} and \code{group2} represent the differences the +\strong{A} and \strong{B} group means from the overall mean, respectively. } \examples{ \dontrun{ @@ -53,8 +65,8 @@ c.sum <- cbind(Intercept = 1, contrasts(mtcars$cyl)) solve(c.sum) #> 4 6 8 #> Intercept 0.333 0.333 0.333 # overall mean -#> 0.667 -0.333 -0.333 # 2/3 * ({2nd, 3rd} - 1st) -#> -0.333 0.667 -0.333 # 2/3 * ({1st, 3rd} - 2nd) +#> 0.667 -0.333 -0.333 # deviation of 1st from overall mean +#> -0.333 0.667 -0.333 # deviation of 2nd from overall mean contrasts(mtcars$cyl) <- contr.deviation @@ -70,8 +82,10 @@ mtcars <- data_modify(mtcars, am = factor(am)) mtcars <- data_arrange(mtcars, select = c("cyl", "am")) mm <- unique(model.matrix(~ cyl * am, data = mtcars)) -rownames(mm) <- c("cyl4.am0", "cyl4.am1", "cyl6.am0", - "cyl6.am1", "cyl8.am0", "cyl8.am1") +rownames(mm) <- c( + "cyl4.am0", "cyl4.am1", "cyl6.am0", + "cyl6.am1", "cyl8.am0", "cyl8.am1" +) solve(mm) #> cyl4.am0 cyl4.am1 cyl6.am0 cyl6.am1 cyl8.am0 cyl8.am1 diff --git a/man/describe_distribution.Rd b/man/describe_distribution.Rd index fd229567d..a23069eea 100644 --- a/man/describe_distribution.Rd +++ b/man/describe_distribution.Rd @@ -50,14 +50,9 @@ describe_distribution(x, ...) \item{...}{Additional arguments to be passed to or from methods.} -\item{centrality}{The point-estimates (centrality indices) to compute. Character -(vector) or list with one or more of these options: \code{"median"}, \code{"mean"}, \code{"MAP"} -(see \code{\link[bayestestR:map_estimate]{map_estimate()}}), \code{"trimmed"} (which is just \code{mean(x, trim = threshold)}), -\code{"mode"} or \code{"all"}.} +\item{centrality}{The point-estimates (centrality indices) to compute. Character (vector) or list with one or more of these options: \code{"median"}, \code{"mean"}, \code{"MAP"} or \code{"all"}.} -\item{dispersion}{Logical, if \code{TRUE}, computes indices of dispersion related -to the estimate(s) (\code{SD} and \code{MAD} for \code{mean} and \code{median}, respectively). -Dispersion is not available for \code{"MAP"} or \code{"mode"} centrality indices.} +\item{dispersion}{Logical, if \code{TRUE}, computes indices of dispersion related to the estimate(s) (\code{SD} and \code{MAD} for \code{mean} and \code{median}, respectively).} \item{iqr}{Logical, if \code{TRUE}, the interquartile range is calculated (based on \code{\link[stats:IQR]{stats::IQR()}}, using \code{type = 6}).} @@ -76,9 +71,7 @@ the first centrality index (which is typically the median).} \item{iterations}{The number of bootstrap replicates for computing confidence intervals. Only applies when \code{ci} is not \code{NULL}.} -\item{threshold}{For \code{centrality = "trimmed"} (i.e. trimmed mean), indicates -the fraction (0 to 0.5) of observations to be trimmed from each end of the -vector before the mean is computed.} +\item{threshold}{For \code{centrality = "trimmed"} (i.e. trimmed mean), indicates the fraction (0 to 0.5) of observations to be trimmed from each end of the vector before the mean is computed.} \item{verbose}{Toggle warnings and messages.} From 6e3182c7eb9602badffb5db94cf3cea8149c193d Mon Sep 17 00:00:00 2001 From: Daniel Date: Thu, 10 Aug 2023 18:46:34 +0200 Subject: [PATCH 11/26] Implement `rowmean_n()` (#445) * draft mean_n() * desc, news * pkgdown * more performant than apply * apply more performant * finalize, add tests * no rounding by default * mean_n -> rowmean_n * address comments * fix test * fix * use rowMeans() * use .coerce_to_dataframe() --------- Co-authored-by: Etienne Bacher <52219252+etiennebacher@users.noreply.github.com> --- DESCRIPTION | 2 +- NAMESPACE | 1 + NEWS.md | 5 ++ R/rowmean_n.R | 101 ++++++++++++++++++++++++++++++++ _pkgdown.yaml | 1 + man/describe_distribution.Rd | 13 +++- man/rowmean_n.Rd | 72 +++++++++++++++++++++++ tests/testthat/test-rowmean_n.R | 26 ++++++++ 8 files changed, 217 insertions(+), 4 deletions(-) create mode 100644 R/rowmean_n.R create mode 100644 man/rowmean_n.Rd create mode 100644 tests/testthat/test-rowmean_n.R diff --git a/DESCRIPTION b/DESCRIPTION index 6a0264ee0..3c71a6343 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Type: Package Package: datawizard Title: Easy Data Wrangling and Statistical Transformations -Version: 0.8.0.4 +Version: 0.8.0.5 Authors@R: c( person("Indrajeet", "Patil", , "patilindrajeet.science@gmail.com", role = "aut", comment = c(ORCID = "0000-0003-1995-6531", Twitter = "@patilindrajeets")), diff --git a/NAMESPACE b/NAMESPACE index 08ec43927..bb2d43766 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -272,6 +272,7 @@ export(reverse) export(reverse_scale) export(row_to_colnames) export(rowid_as_column) +export(rowmean_n) export(rownames_as_column) export(skewness) export(slide) diff --git a/NEWS.md b/NEWS.md index c3aee3b24..529ec1398 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,10 @@ # datawizard (devel) +NEW FUNCTIONS + +* `rowmean_n()`, to compute row means if row contains at least `n` non-missing + values. + CHANGES * `recode_into()` gains an `overwrite` argument to skip overwriting already diff --git a/R/rowmean_n.R b/R/rowmean_n.R new file mode 100644 index 000000000..ab47cf511 --- /dev/null +++ b/R/rowmean_n.R @@ -0,0 +1,101 @@ +#' @title Row means with minimum amount of valid values +#' @name rowmean_n +#' @description This function is similar to the SPSS `MEAN.n` function and computes +#' row means from a data frame or matrix if at least `n` values of a row are +#' valid (and not `NA`). +#' +#' @param data A data frame with at least two columns, where row means are applied. +#' @param n A numeric value of length 1. May either be +#' - a numeric value that indicates the amount of valid values per row to +#' calculate the row mean; +#' - or a value between 0 and 1, indicating a proportion of valid values per +#' row to calculate the row mean (see 'Details'). +#' +#' If a row's sum of valid values is less than `n`, `NA` will be returned. +#' @param digits Numeric value indicating the number of decimal places to be +#' used for rounding mean values. Negative values are allowed (see 'Details'). +#' By default, `digits = NULL` and no rounding is used. +#' @param verbose Toggle warnings. +#' +#' @return A vector with row means for those rows with at least `n` valid values. +#' +#' @details Rounding to a negative number of `digits` means rounding to a power of +#' ten, for example `rowmean_n(df, 3, digits = -2)` rounds to the nearest hundred. +#' For `n`, must be a numeric value from `0` to `ncol(data)`. If a row in the +#' data frame has at least `n` non-missing values, the row mean is returned. If +#' `n` is a non-integer value from 0 to 1, `n` is considered to indicate the +#' proportion of required non-missing values per row. E.g., if `n = 0.75`, a +#' row must have at least `ncol(data) * n` non-missing values for the row mean +#' to be calculated. See 'Examples'. +#' +#' @examples +#' dat <- data.frame( +#' c1 = c(1, 2, NA, 4), +#' c2 = c(NA, 2, NA, 5), +#' c3 = c(NA, 4, NA, NA), +#' c4 = c(2, 3, 7, 8) +#' ) +#' +#' # needs at least 4 non-missing values per row +#' rowmean_n(dat, 4) # 1 valid return value +#' +#' # needs at least 3 non-missing values per row +#' rowmean_n(dat, 3) # 2 valid return values +#' +#' # needs at least 2 non-missing values per row +#' rowmean_n(dat, 2) +#' +#' # needs at least 1 non-missing value per row +#' rowmean_n(dat, 1) # all means are shown +#' +#' # needs at least 50% of non-missing values per row +#' rowmean_n(dat, 0.5) # 3 valid return values +#' +#' # needs at least 75% of non-missing values per row +#' rowmean_n(dat, 0.75) # 2 valid return values +#' +#' @export +rowmean_n <- function(data, n, digits = NULL, verbose = TRUE) { + data <- .coerce_to_dataframe(data) + + # n must be a numeric, non-missing value + if (is.null(n) || all(is.na(n)) || !is.numeric(n) || length(n) > 1) { + insight::format_error("`n` must be a numeric value of length 1.") + } + + # make sure we only have numeric values + numeric_columns <- vapply(data, is.numeric, TRUE) + if (!all(numeric_columns)) { + if (verbose) { + insight::format_alert("Only numeric columns are considered for calculation.") + } + data <- data[numeric_columns] + } + + # check if we have a data framme with at least two columns + if (ncol(data) < 2) { + insight::format_error("`data` must be a data frame with at least two numeric columns.") + } + + # is 'n' indicating a proportion? + decimals <- n %% 1 + if (decimals != 0) { + n <- round(ncol(data) * decimals) + } + + # n may not be larger as df's amount of columns + if (ncol(data) < n) { + insight::format_error("`n` must be smaller or equal to number of columns in data frame.") + } + + # row means + to_na <- rowSums(is.na(data)) > ncol(data) - n + out <- rowMeans(data, na.rm = TRUE) + out[to_na] <- NA + + # round, if requested + if (!is.null(digits) && !all(is.na(digits))) { + out <- round(out, digits = digits) + } + out +} diff --git a/_pkgdown.yaml b/_pkgdown.yaml index 038a405a3..9d321aa78 100644 --- a/_pkgdown.yaml +++ b/_pkgdown.yaml @@ -64,6 +64,7 @@ reference: - smoothness - skewness - weighted_mean + - rowmean_n - mean_sd - title: Convert and Replace Data diff --git a/man/describe_distribution.Rd b/man/describe_distribution.Rd index a23069eea..fd229567d 100644 --- a/man/describe_distribution.Rd +++ b/man/describe_distribution.Rd @@ -50,9 +50,14 @@ describe_distribution(x, ...) \item{...}{Additional arguments to be passed to or from methods.} -\item{centrality}{The point-estimates (centrality indices) to compute. Character (vector) or list with one or more of these options: \code{"median"}, \code{"mean"}, \code{"MAP"} or \code{"all"}.} +\item{centrality}{The point-estimates (centrality indices) to compute. Character +(vector) or list with one or more of these options: \code{"median"}, \code{"mean"}, \code{"MAP"} +(see \code{\link[bayestestR:map_estimate]{map_estimate()}}), \code{"trimmed"} (which is just \code{mean(x, trim = threshold)}), +\code{"mode"} or \code{"all"}.} -\item{dispersion}{Logical, if \code{TRUE}, computes indices of dispersion related to the estimate(s) (\code{SD} and \code{MAD} for \code{mean} and \code{median}, respectively).} +\item{dispersion}{Logical, if \code{TRUE}, computes indices of dispersion related +to the estimate(s) (\code{SD} and \code{MAD} for \code{mean} and \code{median}, respectively). +Dispersion is not available for \code{"MAP"} or \code{"mode"} centrality indices.} \item{iqr}{Logical, if \code{TRUE}, the interquartile range is calculated (based on \code{\link[stats:IQR]{stats::IQR()}}, using \code{type = 6}).} @@ -71,7 +76,9 @@ the first centrality index (which is typically the median).} \item{iterations}{The number of bootstrap replicates for computing confidence intervals. Only applies when \code{ci} is not \code{NULL}.} -\item{threshold}{For \code{centrality = "trimmed"} (i.e. trimmed mean), indicates the fraction (0 to 0.5) of observations to be trimmed from each end of the vector before the mean is computed.} +\item{threshold}{For \code{centrality = "trimmed"} (i.e. trimmed mean), indicates +the fraction (0 to 0.5) of observations to be trimmed from each end of the +vector before the mean is computed.} \item{verbose}{Toggle warnings and messages.} diff --git a/man/rowmean_n.Rd b/man/rowmean_n.Rd new file mode 100644 index 000000000..df340eed3 --- /dev/null +++ b/man/rowmean_n.Rd @@ -0,0 +1,72 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/rowmean_n.R +\name{rowmean_n} +\alias{rowmean_n} +\title{Row means with minimum amount of valid values} +\usage{ +rowmean_n(data, n, digits = NULL, verbose = TRUE) +} +\arguments{ +\item{data}{A data frame with at least two columns, where row means are applied.} + +\item{n}{A numeric value of length 1. May either be +\itemize{ +\item a numeric value that indicates the amount of valid values per row to +calculate the row mean; +\item or a value between 0 and 1, indicating a proportion of valid values per +row to calculate the row mean (see 'Details'). +} + +If a row's sum of valid values is less than \code{n}, \code{NA} will be returned.} + +\item{digits}{Numeric value indicating the number of decimal places to be +used for rounding mean values. Negative values are allowed (see 'Details'). +By default, \code{digits = NULL} and no rounding is used.} + +\item{verbose}{Toggle warnings.} +} +\value{ +A vector with row means for those rows with at least \code{n} valid values. +} +\description{ +This function is similar to the SPSS \code{MEAN.n} function and computes +row means from a data frame or matrix if at least \code{n} values of a row are +valid (and not \code{NA}). +} +\details{ +Rounding to a negative number of \code{digits} means rounding to a power of +ten, for example \code{rowmean_n(df, 3, digits = -2)} rounds to the nearest hundred. +For \code{n}, must be a numeric value from \code{0} to \code{ncol(data)}. If a row in the +data frame has at least \code{n} non-missing values, the row mean is returned. If +\code{n} is a non-integer value from 0 to 1, \code{n} is considered to indicate the +proportion of required non-missing values per row. E.g., if \code{n = 0.75}, a +row must have at least \code{ncol(data) * n} non-missing values for the row mean +to be calculated. See 'Examples'. +} +\examples{ +dat <- data.frame( + c1 = c(1, 2, NA, 4), + c2 = c(NA, 2, NA, 5), + c3 = c(NA, 4, NA, NA), + c4 = c(2, 3, 7, 8) +) + +# needs at least 4 non-missing values per row +rowmean_n(dat, 4) # 1 valid return value + +# needs at least 3 non-missing values per row +rowmean_n(dat, 3) # 2 valid return values + +# needs at least 2 non-missing values per row +rowmean_n(dat, 2) + +# needs at least 1 non-missing value per row +rowmean_n(dat, 1) # all means are shown + +# needs at least 50\% of non-missing values per row +rowmean_n(dat, 0.5) # 3 valid return values + +# needs at least 75\% of non-missing values per row +rowmean_n(dat, 0.75) # 2 valid return values + +} diff --git a/tests/testthat/test-rowmean_n.R b/tests/testthat/test-rowmean_n.R new file mode 100644 index 000000000..a17996ff6 --- /dev/null +++ b/tests/testthat/test-rowmean_n.R @@ -0,0 +1,26 @@ +test_that("rowmean_n", { + d_mn <- data.frame( + c1 = c(1, 2, NA, 4), + c2 = c(NA, 2, NA, 5), + c3 = c(NA, 4, NA, NA), + c4 = c(2, 3, 7, 8) + ) + expect_equal(rowmean_n(d_mn, 4), c(NA, 2.75, NA, NA), tolerance = 1e-3) + expect_equal(rowmean_n(d_mn, 3), c(NA, 2.75, NA, 5.66667), tolerance = 1e-3) + expect_equal(rowmean_n(d_mn, 2), c(1.5, 2.75, NA, 5.66667), tolerance = 1e-3) + expect_equal(rowmean_n(d_mn, 1), c(1.5, 2.75, 7, 5.66667), tolerance = 1e-3) + expect_equal(rowmean_n(d_mn, 0.5), c(1.5, 2.75, NA, 5.66667), tolerance = 1e-3) + expect_equal(rowmean_n(d_mn, 0.75), c(NA, 2.75, NA, 5.66667), tolerance = 1e-3) + expect_equal(rowmean_n(d_mn, 2, digits = 1), c(1.5, 2.8, NA, 5.7), tolerance = 1e-1) +}) + +test_that("rowmean_n, errors or messages", { + data(iris) + expect_error(rowmean_n(5, n = 1), regex = "`data` must be") + expect_error(rowmean_n(iris[1], n = 1), regex = "two numeric") + expect_error(rowmean_n(iris, n = NULL), regex = "numeric value") + expect_error(rowmean_n(iris, n = 1:4), regex = "numeric value") + expect_error(rowmean_n(iris, n = "a"), regex = "numeric value") + expect_message(rowmean_n(iris[1:3, ], n = 3), regex = "Only numeric") + expect_silent(rowmean_n(iris[1:3, ], n = 3, verbose = FALSE)) +}) From 57b193d56d46ae98de2d21007a1c5b1cfd457adc Mon Sep 17 00:00:00 2001 From: Daniel Date: Sat, 12 Aug 2023 15:46:07 +0200 Subject: [PATCH 12/26] Implement `means_by_group()` (#446) * draft grouped mean * add methods * fix * fix * docs * fix printing issues * fix check issues * fix * news, desc * fix issues * add p-value * emmeans to suggests * add ci * fix, tests * snapshots * docs * add tests * docs * round weighted N * fix for weights * skip test if emmeans not installed * typo in news * fix typos in docs --------- Co-authored-by: Etienne Bacher <52219252+etiennebacher@users.noreply.github.com> --- DESCRIPTION | 3 +- NAMESPACE | 7 + NEWS.md | 3 + R/means_by_group.R | 294 ++++++++++++++++++ _pkgdown.yaml | 1 + man/means_by_group.Rd | 125 ++++++++ tests/testthat/_snaps/means_by_group.md | 172 ++++++++++ .../testthat/_snaps/windows/means_by_group.md | 34 ++ tests/testthat/test-labelled_data.R | 36 ++- tests/testthat/test-means_by_group.R | 21 ++ 10 files changed, 678 insertions(+), 18 deletions(-) create mode 100644 R/means_by_group.R create mode 100644 man/means_by_group.Rd create mode 100644 tests/testthat/_snaps/means_by_group.md create mode 100644 tests/testthat/_snaps/windows/means_by_group.md create mode 100644 tests/testthat/test-means_by_group.R diff --git a/DESCRIPTION b/DESCRIPTION index 3c71a6343..d86f68812 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Type: Package Package: datawizard Title: Easy Data Wrangling and Statistical Transformations -Version: 0.8.0.5 +Version: 0.8.0.6 Authors@R: c( person("Indrajeet", "Patil", , "patilindrajeet.science@gmail.com", role = "aut", comment = c(ORCID = "0000-0003-1995-6531", Twitter = "@patilindrajeets")), @@ -43,6 +43,7 @@ Suggests: data.table, dplyr (>= 1.0), effectsize, + emmeans, gamm4, ggplot2, gt, diff --git a/NAMESPACE b/NAMESPACE index bb2d43766..fac5fbaf6 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -67,6 +67,7 @@ S3method(describe_distribution,numeric) S3method(format,data_codebook) S3method(format,dw_data_peek) S3method(format,dw_data_tabulate) +S3method(format,dw_groupmeans) S3method(format,parameters_distribution) S3method(kurtosis,data.frame) S3method(kurtosis,default) @@ -76,6 +77,9 @@ S3method(labels_to_levels,data.frame) S3method(labels_to_levels,default) S3method(labels_to_levels,factor) S3method(makepredictcall,dw_transformer) +S3method(means_by_group,data.frame) +S3method(means_by_group,default) +S3method(means_by_group,numeric) S3method(normalize,data.frame) S3method(normalize,factor) S3method(normalize,grouped_df) @@ -86,6 +90,8 @@ S3method(print,data_codebook) S3method(print,dw_data_peek) S3method(print,dw_data_tabulate) S3method(print,dw_data_tabulates) +S3method(print,dw_groupmeans) +S3method(print,dw_groupmeans_list) S3method(print,dw_transformer) S3method(print,parameters_distribution) S3method(print,parameters_kurtosis) @@ -252,6 +258,7 @@ export(get_columns) export(kurtosis) export(labels_to_levels) export(mean_sd) +export(means_by_group) export(median_mad) export(normalize) export(print_html) diff --git a/NEWS.md b/NEWS.md index 529ec1398..858b95f93 100644 --- a/NEWS.md +++ b/NEWS.md @@ -5,6 +5,9 @@ NEW FUNCTIONS * `rowmean_n()`, to compute row means if row contains at least `n` non-missing values. +* `means_by_group()`, to compute mean values of variables, grouped by levels + of specified factors. + CHANGES * `recode_into()` gains an `overwrite` argument to skip overwriting already diff --git a/R/means_by_group.R b/R/means_by_group.R new file mode 100644 index 000000000..1d3f6fd52 --- /dev/null +++ b/R/means_by_group.R @@ -0,0 +1,294 @@ +#' @title Summary of mean values by group +#' @name means_by_group +#' +#' @description Computes summary table of means by groups. +#' +#' @param x A vector or a data frame. +#' @param group If `x` is a numeric vector, `group` should be a factor that +#' indicates the group-classifying categories. If `x` is a data frame, `group` +#' should be a character string, naming the variable in `x` that is used for +#' grouping. Numeric vectors are coerced to factors. Not that `group` should +#' only refer to a single variable. +#' @param ci Level of confidence interval for mean estimates. Default is `0.95`. +#' Use `ci = NA` to suppress confidence intervals. +#' @param weights If `x` is a numeric vector, `weights` should be a vector of +#' weights that will be applied to weight all observations. If `x` is a data +#' frame, `weights` can also be a character string indicating the name of the +#' variable in `x` that should be used for weighting. Default is `NULL`, so no +#' weights are used. +#' @param digits Optional scalar, indicating the amount of digits after decimal +#' point when rounding estimates and values. +#' @param ... Currently not used +#' @inheritParams find_columns +#' +#' @return A data frame with information on mean and further summary statistics +#' for each sub-group. +#' +#' @details This function is comparable to `aggregate(x, group, mean)`, but provides +#' some further information, including summary statistics from a One-Way-ANOVA +#' using `x` as dependent and `group` as independent variable. [`emmeans::contrast()`] +#' is used to get p-values for each sub-group. P-values indicate whether each +#' group-mean is significantly different from the total mean. +#' +#' @examples +#' data(efc) +#' means_by_group(efc, "c12hour", "e42dep") +#' +#' data(iris) +#' means_by_group(iris, "Sepal.Width", "Species") +#' +#' # weighting +#' efc$weight <- abs(rnorm(n = nrow(efc), mean = 1, sd = .5)) +#' means_by_group(efc, "c12hour", "e42dep", weights = "weight") +#' @export +means_by_group <- function(x, ...) { + UseMethod("means_by_group") +} + + +#' @export +means_by_group.default <- function(x, ...) { + insight::format_error("`means_by_group()` does not work for objects of class `", class(x)[1], "`.") +} + + +#' @rdname means_by_group +#' @export +means_by_group.numeric <- function(x, + group = NULL, + ci = 0.95, + weights = NULL, + digits = NULL, + ...) { + # sanity check for arguments + + # "group" must be provided + if (is.null(group)) { + insight::format_error("Argument `group` is missing.") + } + + # group must be of same length as x + if (length(group) != length(x)) { + insight::format_error("Argument `group` must be of same length as `x`.") + } + + # if weights are provided, must be of same length as x + if (!is.null(weights) && length(weights) != length(x)) { + insight::format_error("Argument `weights` must be of same length as `x`.") + } + + # if weights are NULL, set weights to 1 + if (is.null(weights)) weights <- rep(1, length(x)) + + # retrieve labels + var_mean_label <- attr(x, "label", exact = TRUE) + var_grp_label <- attr(group, "label", exact = TRUE) + + # if no labels present, use variable names directly + if (is.null(var_mean_label)) { + var_mean_label <- deparse(substitute(x)) + } + if (is.null(var_grp_label)) { + var_grp_label <- deparse(substitute(group)) + } + + # coerce group to factor if numeric, or convert labels to levels, if factor + if (is.factor(group)) { + group <- tryCatch(labels_to_levels(group, verbose = FALSE), error = function(e) group) + } else { + group <- to_factor(group) + } + + data <- stats::na.omit(data.frame( + x = x, + group = group, + weights = weights, + stringsAsFactors = FALSE + )) + + # get grouped means table + out <- .means_by_group(data, ci = ci) + + # attributes + attr(out, "var_mean_label") <- var_mean_label + attr(out, "var_grp_label") <- var_grp_label + attr(out, "digits") <- digits + + class(out) <- c("dw_groupmeans", "data.frame") + out +} + + +#' @rdname means_by_group +#' @export +means_by_group.data.frame <- function(x, + select = NULL, + group = NULL, + ci = 0.95, + weights = NULL, + digits = NULL, + exclude = NULL, + ignore_case = FALSE, + regex = FALSE, + verbose = TRUE, + ...) { + # evaluate select/exclude, may be select-helpers + select <- .select_nse(select, + x, + exclude, + ignore_case, + regex = regex, + verbose = verbose + ) + + if (is.null(weights)) { + w <- NULL + } else if (is.character(weights)) { + w <- x[[weights]] + } else { + w <- weights + } + + out <- lapply(select, function(i) { + # if no labels present, use variable names directy + if (is.null(attr(x[[i]], "label", exact = TRUE))) { + attr(x[[i]], "label") <- i + } + if (is.null(attr(x[[group]], "label", exact = TRUE))) { + attr(x[[group]], "label") <- group + } + # compute means table + means_by_group(x[[i]], group = x[[group]], ci = ci, weights = w, digits = digits, ...) + }) + + class(out) <- c("dw_groupmeans_list", "list") + out +} + + +#' @keywords internal +.means_by_group <- function(data, ci = 0.95) { + # compute anova statistics for mean table + if (is.null(data$weights) || all(data$weights == 1)) { + fit <- stats::lm(x ~ group, data = data) + } else { + fit <- stats::lm(x ~ group, weights = data$weights, data = data) + } + + # summary table data + groups <- split(data$x, data$group) + group_weights <- split(data$weights, data$group) + out <- do.call(rbind, Map(function(x, w) { + data.frame( + Mean = weighted_mean(x, weights = w), + SD = weighted_sd(x, weights = w), + N = round(sum(w)), + stringsAsFactors = FALSE + ) + }, groups, group_weights)) + + # add group names + out$Category <- levels(data$group) + out$p <- out$CI_high <- out$CI_low <- NA + + # p-values of contrast-means + if (insight::check_if_installed("emmeans", quietly = TRUE)) { + # create summary table of contrasts, for p-values and confidence intervals + predicted <- emmeans::emmeans(fit, specs = "group", level = ci) + contrasts <- emmeans::contrast(predicted, method = "eff") + # add p-values and confidence intervals to "out" + if (!is.null(ci) && !is.na(ci)) { + summary_table <- as.data.frame(predicted) + out$CI_low <- summary_table$lower.CL + out$CI_high <- summary_table$upper.CL + } + summary_table <- as.data.frame(contrasts) + out$p <- summary_table$p.value + } + + # reorder columns + out <- out[c("Category", "Mean", "N", "SD", "CI_low", "CI_high", "p")] + + # finally, add total-row + out <- rbind( + out, + data.frame( + Category = "Total", + Mean = weighted_mean(data$x, weights = data$weights), + N = nrow(data), + SD = weighted_sd(data$x, weights = data$weights), + CI_low = NA, + CI_high = NA, + p = NA, + stringsAsFactors = FALSE + ) + ) + + # get anova statistics for mean table + sum.fit <- summary(fit) + + # r-squared values + r2 <- sum.fit$r.squared + r2.adj <- sum.fit$adj.r.squared + + # F-statistics + fstat <- sum.fit$fstatistic + pval <- stats::pf(fstat[1], fstat[2], fstat[3], lower.tail = FALSE) + + # copy as attributes + attr(out, "r2") <- r2 + attr(out, "ci") <- ci + attr(out, "adj.r2") <- r2.adj + attr(out, "fstat") <- fstat[1] + attr(out, "p.value") <- pval + + out +} + + +# methods ----------------- + +#' @export +format.dw_groupmeans <- function(x, digits = NULL, ...) { + if (is.null(digits)) { + digits <- attr(x, "digits", exact = TRUE) + } + if (is.null(digits)) { + digits <- 2 + } + x$N <- insight::format_value(x$N, digits = 0) + insight::format_table(remove_empty_columns(x), digits = digits, ...) +} + +#' @export +print.dw_groupmeans <- function(x, digits = NULL, ...) { + out <- format(x, digits = digits, ...) + + # caption + l1 <- attributes(x)$var_mean_label + l2 <- attributes(x)$var_grp_label + if (!is.null(l1) && !is.null(l2)) { + caption <- c(paste0("# Mean of ", l1, " by ", l2), "blue") + } else { + caption <- NULL + } + + # footer + footer <- paste0( + "\nAnova: R2=", insight::format_value(attributes(x)$r2, digits = 3), + "; adj.R2=", insight::format_value(attributes(x)$adj.r2, digits = 3), + "; F=", insight::format_value(attributes(x)$fstat, digits = 3), + "; ", insight::format_p(attributes(x)$p.value, whitespace = FALSE), + "\n" + ) + + cat(insight::export_table(out, caption = caption, footer = footer, ...)) +} + +#' @export +print.dw_groupmeans_list <- function(x, digits = NULL, ...) { + for (i in seq_along(x)) { + if (i > 1) cat("\n") + print(x[[i]], digits = digits, ...) + } +} diff --git a/_pkgdown.yaml b/_pkgdown.yaml index 9d321aa78..1da6b0661 100644 --- a/_pkgdown.yaml +++ b/_pkgdown.yaml @@ -59,6 +59,7 @@ reference: - data_codebook - data_tabulate - data_peek + - means_by_group - contains("distribution") - kurtosis - smoothness diff --git a/man/means_by_group.Rd b/man/means_by_group.Rd new file mode 100644 index 000000000..9434452ad --- /dev/null +++ b/man/means_by_group.Rd @@ -0,0 +1,125 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/means_by_group.R +\name{means_by_group} +\alias{means_by_group} +\alias{means_by_group.numeric} +\alias{means_by_group.data.frame} +\title{Summary of mean values by group} +\usage{ +means_by_group(x, ...) + +\method{means_by_group}{numeric}(x, group = NULL, ci = 0.95, weights = NULL, digits = NULL, ...) + +\method{means_by_group}{data.frame}( + x, + select = NULL, + group = NULL, + ci = 0.95, + weights = NULL, + digits = NULL, + exclude = NULL, + ignore_case = FALSE, + regex = FALSE, + verbose = TRUE, + ... +) +} +\arguments{ +\item{x}{A vector or a data frame.} + +\item{...}{Currently not used} + +\item{group}{If \code{x} is a numeric vector, \code{group} should be a factor that +indicates the group-classifying categories. If \code{x} is a data frame, \code{group} +should be a character string, naming the variable in \code{x} that is used for +grouping. Numeric vectors are coerced to factors. Not that \code{group} should +only refer to a single variable.} + +\item{ci}{Level of confidence interval for mean estimates. Default is \code{0.95}. +Use \code{ci = NA} to suppress confidence intervals.} + +\item{weights}{If \code{x} is a numeric vector, \code{weights} should be a vector of +weights that will be applied to weight all observations. If \code{x} is a data +frame, \code{weights} can also be a character string indicating the name of the +variable in \code{x} that should be used for weighting. Default is \code{NULL}, so no +weights are used.} + +\item{digits}{Optional scalar, indicating the amount of digits after decimal +point when rounding estimates and values.} + +\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"}), or a character +vector of variable names (e.g., \code{c("col1", "col2", "col3")}), +\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")}. +\item or 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{find_columns(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{verbose}{Toggle warnings.} +} +\value{ +A data frame with information on mean and further summary statistics +for each sub-group. +} +\description{ +Computes summary table of means by groups. +} +\details{ +This function is comparable to \code{aggregate(x, group, mean)}, but provides +some further information, including summary statistics from a One-Way-ANOVA +using \code{x} as dependent and \code{group} as independent variable. \code{\link[emmeans:contrast]{emmeans::contrast()}} +is used to get p-values for each sub-group. P-values indicate whether each +group-mean is significantly different from the total mean. +} +\examples{ +data(efc) +means_by_group(efc, "c12hour", "e42dep") + +data(iris) +means_by_group(iris, "Sepal.Width", "Species") + +# weighting +efc$weight <- abs(rnorm(n = nrow(efc), mean = 1, sd = .5)) +means_by_group(efc, "c12hour", "e42dep", weights = "weight") +} diff --git a/tests/testthat/_snaps/means_by_group.md b/tests/testthat/_snaps/means_by_group.md new file mode 100644 index 000000000..78a43d8b4 --- /dev/null +++ b/tests/testthat/_snaps/means_by_group.md @@ -0,0 +1,172 @@ +# meany_by_group + + Code + means_by_group(efc, "c12hour", "e42dep") + Output + # Mean of average number of hours of care per week by elder's dependency + + Category | Mean | N | SD | 95% CI | p + ---------------------------------------------------------------------- + independent | 17.00 | 2 | 11.31 | [-68.46, 102.46] | 0.573 + slightly dependent | 34.25 | 4 | 29.97 | [-26.18, 94.68] | 0.626 + moderately dependent | 52.75 | 28 | 51.83 | [ 29.91, 75.59] | > .999 + severely dependent | 106.97 | 63 | 65.88 | [ 91.74, 122.19] | 0.001 + Total | 86.46 | 97 | 66.40 | | + + Anova: R2=0.186; adj.R2=0.160; F=7.098; p<.001 + +--- + + Code + means_by_group(efc, "c12hour", "e42dep", ci = 0.99) + Output + # Mean of average number of hours of care per week by elder's dependency + + Category | Mean | N | SD | 99% CI | p + ---------------------------------------------------------------------- + independent | 17.00 | 2 | 11.31 | [-96.17, 130.17] | 0.573 + slightly dependent | 34.25 | 4 | 29.97 | [-45.77, 114.27] | 0.626 + moderately dependent | 52.75 | 28 | 51.83 | [ 22.50, 83.00] | > .999 + severely dependent | 106.97 | 63 | 65.88 | [ 86.80, 127.13] | 0.001 + Total | 86.46 | 97 | 66.40 | | + + Anova: R2=0.186; adj.R2=0.160; F=7.098; p<.001 + +--- + + Code + means_by_group(efc, "c12hour", "e42dep", ci = NA) + Output + # Mean of average number of hours of care per week by elder's dependency + + Category | Mean | N | SD | p + --------------------------------------------------- + independent | 17.00 | 2 | 11.31 | 0.573 + slightly dependent | 34.25 | 4 | 29.97 | 0.626 + moderately dependent | 52.75 | 28 | 51.83 | > .999 + severely dependent | 106.97 | 63 | 65.88 | 0.001 + Total | 86.46 | 97 | 66.40 | + + Anova: R2=0.186; adj.R2=0.160; F=7.098; p<.001 + +--- + + Code + means_by_group(efc, c("neg_c_7", "c12hour"), "e42dep") + Output + # Mean of Negative impact with 7 items by elder's dependency + + Category | Mean | N | SD | 95% CI | p + ----------------------------------------------------------------- + independent | 11.00 | 2 | 0.00 | [ 5.00, 17.00] | 0.567 + slightly dependent | 10.00 | 4 | 3.16 | [ 5.76, 14.24] | 0.296 + moderately dependent | 13.71 | 28 | 3.14 | [12.11, 15.32] | 0.296 + severely dependent | 14.67 | 60 | 4.78 | [13.57, 15.76] | 0.108 + Total | 14.11 | 94 | 4.34 | | + + Anova: R2=0.063; adj.R2=0.032; F=2.009; p=0.118 + + # Mean of average number of hours of care per week by elder's dependency + + Category | Mean | N | SD | 95% CI | p + ---------------------------------------------------------------------- + independent | 17.00 | 2 | 11.31 | [-68.46, 102.46] | 0.573 + slightly dependent | 34.25 | 4 | 29.97 | [-26.18, 94.68] | 0.626 + moderately dependent | 52.75 | 28 | 51.83 | [ 29.91, 75.59] | > .999 + severely dependent | 106.97 | 63 | 65.88 | [ 91.74, 122.19] | 0.001 + Total | 86.46 | 97 | 66.40 | | + + Anova: R2=0.186; adj.R2=0.160; F=7.098; p<.001 + +--- + + Code + means_by_group(efc, c("neg_c_7", "c12hour"), "e42dep", ci = NA) + Output + # Mean of Negative impact with 7 items by elder's dependency + + Category | Mean | N | SD | p + ------------------------------------------------ + independent | 11.00 | 2 | 0.00 | 0.567 + slightly dependent | 10.00 | 4 | 3.16 | 0.296 + moderately dependent | 13.71 | 28 | 3.14 | 0.296 + severely dependent | 14.67 | 60 | 4.78 | 0.108 + Total | 14.11 | 94 | 4.34 | + + Anova: R2=0.063; adj.R2=0.032; F=2.009; p=0.118 + + # Mean of average number of hours of care per week by elder's dependency + + Category | Mean | N | SD | p + --------------------------------------------------- + independent | 17.00 | 2 | 11.31 | 0.573 + slightly dependent | 34.25 | 4 | 29.97 | 0.626 + moderately dependent | 52.75 | 28 | 51.83 | > .999 + severely dependent | 106.97 | 63 | 65.88 | 0.001 + Total | 86.46 | 97 | 66.40 | + + Anova: R2=0.186; adj.R2=0.160; F=7.098; p<.001 + +--- + + Code + means_by_group(efc, c("neg_c_7", "c12hour"), "e42dep", ci = 0.99) + Output + # Mean of Negative impact with 7 items by elder's dependency + + Category | Mean | N | SD | 99% CI | p + ----------------------------------------------------------------- + independent | 11.00 | 2 | 0.00 | [ 3.05, 18.95] | 0.567 + slightly dependent | 10.00 | 4 | 3.16 | [ 4.38, 15.62] | 0.296 + moderately dependent | 13.71 | 28 | 3.14 | [11.59, 15.84] | 0.296 + severely dependent | 14.67 | 60 | 4.78 | [13.22, 16.12] | 0.108 + Total | 14.11 | 94 | 4.34 | | + + Anova: R2=0.063; adj.R2=0.032; F=2.009; p=0.118 + + # Mean of average number of hours of care per week by elder's dependency + + Category | Mean | N | SD | 99% CI | p + ---------------------------------------------------------------------- + independent | 17.00 | 2 | 11.31 | [-96.17, 130.17] | 0.573 + slightly dependent | 34.25 | 4 | 29.97 | [-45.77, 114.27] | 0.626 + moderately dependent | 52.75 | 28 | 51.83 | [ 22.50, 83.00] | > .999 + severely dependent | 106.97 | 63 | 65.88 | [ 86.80, 127.13] | 0.001 + Total | 86.46 | 97 | 66.40 | | + + Anova: R2=0.186; adj.R2=0.160; F=7.098; p<.001 + +--- + + Code + means_by_group(efc$c12hour, efc$e42dep) + Output + # Mean of average number of hours of care per week by elder's dependency + + Category | Mean | N | SD | 95% CI | p + ---------------------------------------------------------------------- + independent | 17.00 | 2 | 11.31 | [-68.46, 102.46] | 0.573 + slightly dependent | 34.25 | 4 | 29.97 | [-26.18, 94.68] | 0.626 + moderately dependent | 52.75 | 28 | 51.83 | [ 29.91, 75.59] | > .999 + severely dependent | 106.97 | 63 | 65.88 | [ 91.74, 122.19] | 0.001 + Total | 86.46 | 97 | 66.40 | | + + Anova: R2=0.186; adj.R2=0.160; F=7.098; p<.001 + +--- + + Code + means_by_group(efc$c12hour, efc$e42dep, ci = NA) + Output + # Mean of average number of hours of care per week by elder's dependency + + Category | Mean | N | SD | p + --------------------------------------------------- + independent | 17.00 | 2 | 11.31 | 0.573 + slightly dependent | 34.25 | 4 | 29.97 | 0.626 + moderately dependent | 52.75 | 28 | 51.83 | > .999 + severely dependent | 106.97 | 63 | 65.88 | 0.001 + Total | 86.46 | 97 | 66.40 | + + Anova: R2=0.186; adj.R2=0.160; F=7.098; p<.001 + diff --git a/tests/testthat/_snaps/windows/means_by_group.md b/tests/testthat/_snaps/windows/means_by_group.md new file mode 100644 index 000000000..198069da9 --- /dev/null +++ b/tests/testthat/_snaps/windows/means_by_group.md @@ -0,0 +1,34 @@ +# meany_by_group, weighted + + Code + means_by_group(efc, "c12hour", "e42dep", weights = "weight") + Output + # Mean of average number of hours of care per week by elder's dependency + + Category | Mean | N | SD | 95% CI | p + ---------------------------------------------------------------------- + independent | 16.92 | 3 | 11.31 | [-60.82, 94.66] | 0.486 + slightly dependent | 33.56 | 4 | 29.75 | [-26.93, 94.05] | 0.593 + moderately dependent | 52.74 | 26 | 54.44 | [ 28.71, 76.76] | 0.996 + severely dependent | 108.08 | 67 | 65.40 | [ 93.01, 123.16] | < .001 + Total | 88.11 | 97 | 67.01 | | + + Anova: R2=0.191; adj.R2=0.165; F=7.329; p<.001 + +--- + + Code + means_by_group(efc, "c12hour", "e42dep", weights = "weight", ci = NA) + Output + # Mean of average number of hours of care per week by elder's dependency + + Category | Mean | N | SD | p + --------------------------------------------------- + independent | 16.92 | 3 | 11.31 | 0.486 + slightly dependent | 33.56 | 4 | 29.75 | 0.593 + moderately dependent | 52.74 | 26 | 54.44 | 0.996 + severely dependent | 108.08 | 67 | 65.40 | < .001 + Total | 88.11 | 97 | 67.01 | + + Anova: R2=0.191; adj.R2=0.165; F=7.329; p<.001 + diff --git a/tests/testthat/test-labelled_data.R b/tests/testthat/test-labelled_data.R index b0f92c730..0b7e37a4d 100644 --- a/tests/testthat/test-labelled_data.R +++ b/tests/testthat/test-labelled_data.R @@ -4,13 +4,13 @@ data(efc, package = "datawizard") test_that("reverse, labels preserved", { # factor, label - expect_equal( + expect_identical( attr(reverse(efc$e42dep), "label", exact = TRUE), "elder's dependency" ) # factor, labels - expect_equal( - names(attr(reverse(efc$e42dep), "labels", exact = TRUE)), + expect_named( + attr(reverse(efc$e42dep), "labels", exact = TRUE), names(attr(efc$e42dep, "labels", exact = TRUE)) ) expect_equal( @@ -19,13 +19,13 @@ test_that("reverse, labels preserved", { ignore_attr = TRUE ) # numeric - expect_equal( - names(attr(reverse(efc$c12hour), "labels", exact = TRUE)), + expect_named( + attr(reverse(efc$c12hour), "labels", exact = TRUE), names(attr(efc$c12hour, "labels", exact = TRUE)) ) # data frame - labels <- sapply(reverse(efc), function(i) attr(i, "label", exact = TRUE)) - expect_equal( + labels <- sapply(reverse(efc), attr, which = "label", exact = TRUE) + expect_identical( labels, c( c12hour = "average number of hours of care per week", @@ -42,8 +42,8 @@ test_that("reverse, labels preserved", { # data_merge ----------------------------------- test_that("data_merge, labels preserved", { - labels <- sapply(data_merge(efc[c(1:2)], efc[c(3:4)], verbose = FALSE), function(i) attr(i, "label", exact = TRUE)) - expect_equal( + labels <- sapply(data_merge(efc[1:2], efc[3:4], verbose = FALSE), attr, which = "label", exact = TRUE) + expect_identical( labels, c( c12hour = "average number of hours of care per week", @@ -72,8 +72,8 @@ test_that("data_extract, labels preserved", { ignore_attr = TRUE ) # data frame - labels <- sapply(data_extract(efc, select = c("e42dep", "c172code")), function(i) attr(i, "label", exact = TRUE)) - expect_equal( + labels <- sapply(data_extract(efc, select = c("e42dep", "c172code")), attr, which = "label", exact = TRUE) + expect_identical( labels, c(e42dep = "elder's dependency", c172code = "carer's level of education") ) @@ -142,8 +142,8 @@ test_that("data_rename, labels preserved", { ignore_attr = TRUE ) # data frame - labels <- sapply(data_remove(efc, starts_with("c1")), function(i) attr(i, "label", exact = TRUE)) - expect_equal( + labels <- sapply(data_remove(efc, starts_with("c1")), attr, which = "label", exact = TRUE) + expect_identical( labels, c(e16sex = "elder's gender", e42dep = "elder's dependency", neg_c_7 = "Negative impact with 7 items") ) @@ -255,12 +255,12 @@ test_that("data_match, labels preserved", { test_that("data_filter, labels preserved", { x <- data_filter(efc, c172code == 1 & c12hour > 40) # factor - expect_equal( + expect_identical( attr(x$e42dep, "label", exact = TRUE), attr(efc$e42dep, "label", exact = TRUE) ) # numeric - expect_equal( + expect_identical( attr(x$c12hour, "label", exact = TRUE), attr(efc$c12hour, "label", exact = TRUE) ) @@ -271,7 +271,9 @@ test_that("data_filter, labels preserved", { # convert_to_na ----------------------------------- test_that("convert_to_na, labels preserved", { - expect_message(x <- convert_to_na(efc, na = c(2, "2"), select = starts_with("e"))) + expect_message({ + x <- convert_to_na(efc, na = c(2, "2"), select = starts_with("e")) + }) # factor expect_equal( attr(x$e42dep, "label", exact = TRUE), @@ -301,7 +303,7 @@ test_that("convert_to_na, labels preserved", { ) # drop unused value labels x <- convert_to_na(efc$c172code, na = 2) - expect_equal( + expect_identical( attr(x, "labels", exact = TRUE), c(`low level of education` = 1, `high level of education` = 3) ) diff --git a/tests/testthat/test-means_by_group.R b/tests/testthat/test-means_by_group.R new file mode 100644 index 000000000..49226fa34 --- /dev/null +++ b/tests/testthat/test-means_by_group.R @@ -0,0 +1,21 @@ +test_that("mean_by_group", { + skip_if_not_installed("emmeans") + data(efc) + expect_snapshot(means_by_group(efc, "c12hour", "e42dep")) + expect_snapshot(means_by_group(efc, "c12hour", "e42dep", ci = 0.99)) + expect_snapshot(means_by_group(efc, "c12hour", "e42dep", ci = NA)) + expect_snapshot(means_by_group(efc, c("neg_c_7", "c12hour"), "e42dep")) + expect_snapshot(means_by_group(efc, c("neg_c_7", "c12hour"), "e42dep", ci = NA)) + expect_snapshot(means_by_group(efc, c("neg_c_7", "c12hour"), "e42dep", ci = 0.99)) + expect_snapshot(means_by_group(efc$c12hour, efc$e42dep)) + expect_snapshot(means_by_group(efc$c12hour, efc$e42dep, ci = NA)) +}) + +test_that("mean_by_group, weighted", { + skip_if_not_installed("emmeans") + data(efc) + set.seed(123) + efc$weight <- abs(rnorm(n = nrow(efc), mean = 1, sd = 0.5)) + expect_snapshot(means_by_group(efc, "c12hour", "e42dep", weights = "weight"), variant = "windows") + expect_snapshot(means_by_group(efc, "c12hour", "e42dep", weights = "weight", ci = NA), variant = "windows") +}) From c8f8a17fb4343bc6e3a9dedf9f6facb1e5f2f318 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20Th=C3=A9riault?= <13123390+rempsyc@users.noreply.github.com> Date: Mon, 14 Aug 2023 04:47:14 -0400 Subject: [PATCH 13/26] Bump `insight` version for `.get_dep_version` (#449) bump version for `.get_dep_version` --- DESCRIPTION | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index d86f68812..6414d5fba 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -33,7 +33,7 @@ BugReports: https://github.com/easystats/datawizard/issues Depends: R (>= 3.6) Imports: - insight (>= 0.19.1), + insight (>= 0.19.3.2), stats, utils Suggests: @@ -78,3 +78,4 @@ Config/Needs/website: rstudio/bslib, r-lib/pkgdown, easystats/easystatstemplate +Remotes: easystats/insight From a1e06207a3e8f866af714154f08ad24780be2246 Mon Sep 17 00:00:00 2001 From: Etienne Bacher <52219252+etiennebacher@users.noreply.github.com> Date: Thu, 17 Aug 2023 08:27:26 +0200 Subject: [PATCH 14/26] Switch from GPL-3 to MIT license (#450) * switch from GPL-3 to MIT license * remove license from rbuildignore * bump NEWS and description [skip ci] --- .Rbuildignore | 1 - DESCRIPTION | 4 +- LICENSE | 676 +------------------------------------------------- LICENSE.md | 21 ++ NEWS.md | 2 + 5 files changed, 27 insertions(+), 677 deletions(-) create mode 100644 LICENSE.md diff --git a/.Rbuildignore b/.Rbuildignore index 74fc7c855..d245bf8c3 100644 --- a/.Rbuildignore +++ b/.Rbuildignore @@ -46,6 +46,5 @@ references.bib ^hextools/. ^WIP/. ^CRAN-SUBMISSION$ -^LICENSE$ docs ^.dev$ diff --git a/DESCRIPTION b/DESCRIPTION index 6414d5fba..1c68c50f1 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Type: Package Package: datawizard Title: Easy Data Wrangling and Statistical Transformations -Version: 0.8.0.6 +Version: 0.8.0.7 Authors@R: c( person("Indrajeet", "Patil", , "patilindrajeet.science@gmail.com", role = "aut", comment = c(ORCID = "0000-0003-1995-6531", Twitter = "@patilindrajeets")), @@ -27,7 +27,7 @@ Description: A lightweight package to assist in key steps involved in any data (3) compute statistical summaries of data properties and distributions. It is also the data wrangling backend for packages in 'easystats' ecosystem. References: Patil et al. (2022) . -License: GPL (>= 3) +License: MIT + file LICENSE URL: https://easystats.github.io/datawizard/ BugReports: https://github.com/easystats/datawizard/issues Depends: diff --git a/LICENSE b/LICENSE index 61d18602b..847d54a99 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,2 @@ -GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. \ No newline at end of file +YEAR: 2023 +COPYRIGHT HOLDER: datawizard authors diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 000000000..e8e0fe91d --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +# MIT License + +Copyright (c) 2023 datawizard authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/NEWS.md b/NEWS.md index 858b95f93..9f479a117 100644 --- a/NEWS.md +++ b/NEWS.md @@ -13,6 +13,8 @@ CHANGES * `recode_into()` gains an `overwrite` argument to skip overwriting already recoded cases when multiple recode patterns apply to the same case. +* `datawizard` moves from the GPL-3 license to the MIT license. + BUG FIXES * Fixed issues in `data_write()` when writing labelled data into SPSS format From 7c86d71bcd3b525229cd231605bf1fb641478a96 Mon Sep 17 00:00:00 2001 From: "Mattan S. Ben-Shachar" Date: Wed, 23 Aug 2023 16:06:38 +0300 Subject: [PATCH 15/26] fix docs --- R/contrs.R | 41 +++++++++++++++++++++-------------------- man/contr.deviation.Rd | 41 +++++++++++++++++++++-------------------- 2 files changed, 42 insertions(+), 40 deletions(-) diff --git a/R/contrs.R b/R/contrs.R index cb1c69722..e1d23f084 100644 --- a/R/contrs.R +++ b/R/contrs.R @@ -5,34 +5,35 @@ #' @inheritParams stats::contr.sum #' #' @details -#' In effects coding, unlike treatment/dummy coding ([stats::contr.treatment()]), each -#' contrast sums to 0. In regressions models, this results in an intercept that -#' represents the (unweighted) average of the group means. In ANOVA settings, -#' this also guarantees that lower order effects represent _main_ effects (and -#' not _simple_ or _conditional_ effects, as is the case when using R's default -#' [stats::contr.treatment()]). +#' In effects coding, unlike treatment/dummy coding +#' ([stats::contr.treatment()]), each contrast sums to 0. In regressions models, +#' this results in an intercept that represents the (unweighted) average of the +#' group means. In ANOVA settings, this also guarantees that lower order effects +#' represent _main_ effects (and not _simple_ or _conditional_ effects, as is +#' the case when using R's default [stats::contr.treatment()]). #' \cr\cr -#' Deviation coding (`contr.deviation`) is a type of effects coding. -#' With deviation coding, the coefficients for factor variables are interpreted -#' as the difference of each factor level from the base level -#' (this is the same interpretation as with treatment/dummy coding). -#' For example, for a factor `group` with levels "A", "B", and "C", with `contr.devation`, -#' the intercept represents the overall mean (average of the group means for the 3 groups), +#' Deviation coding (`contr.deviation`) is a type of effects coding. With +#' deviation coding, the coefficients for factor variables are interpreted as +#' the difference of each factor level from the base level (this is the same +#' interpretation as with treatment/dummy coding). For example, for a factor +#' `group` with levels "A", "B", and "C", with `contr.devation`, the intercept +#' represents the overall mean (average of the group means for the 3 groups), #' and the coefficients `groupB` and `groupC` represent the differences between #' the A group mean and the B and C group means, respectively. #' \cr\cr -#' Sum coding ([stats::contr.sum()]) is another type of effects coding. -#' With sum coding, the coefficients for factor variables are interpreted -#' as the difference of each factor level from **the grand (across-groups) mean**. -#' For example, for a factor `group` with levels "A", "B", and "C", with `contr.sum`, -#' the intercept represents the overall mean (average of the group means for the 3 groups), -#' and the coefficients `group1` and `group2` represent the differences the +#' Sum coding ([stats::contr.sum()]) is another type of effects coding. With sum +#' coding, the coefficients for factor variables are interpreted as the +#' difference of each factor level from **the grand (across-groups) mean**. For +#' example, for a factor `group` with levels "A", "B", and "C", with +#' `contr.sum`, the intercept represents the overall mean (average of the group +#' means for the 3 groups), and the coefficients `group1` and `group2` represent +#' the differences the #' **A** and **B** group means from the overall mean, respectively. #' #' @seealso [stats::contr.sum()] #' #' @examples -#' \dontrun{ +#' if (FALSE) { #' data("mtcars") #' #' mtcars <- data_modify(mtcars, cyl = factor(cyl)) @@ -62,7 +63,7 @@ #' #> 8 -1.000 0.000 1.000 # 3rd level - 1st level #' #' ## With Interactions ----------------------------------------- -#' mtcars <- data_modify(mtcars, am = factor(am)) +#' mtcars <- data_modify(mtcars, am = C(am, contr = contr.deviation)) #' mtcars <- data_arrange(mtcars, select = c("cyl", "am")) #' #' mm <- unique(model.matrix(~ cyl * am, data = mtcars)) diff --git a/man/contr.deviation.Rd b/man/contr.deviation.Rd index f44106111..09b8b3279 100644 --- a/man/contr.deviation.Rd +++ b/man/contr.deviation.Rd @@ -23,32 +23,33 @@ contr.deviation(n, base = 1, contrasts = TRUE, sparse = FALSE) Build a deviation contrast matrix, a type of \emph{effects contrast} matrix. } \details{ -In effects coding, unlike treatment/dummy coding (\code{\link[stats:contrast]{stats::contr.treatment()}}), each -contrast sums to 0. In regressions models, this results in an intercept that -represents the (unweighted) average of the group means. In ANOVA settings, -this also guarantees that lower order effects represent \emph{main} effects (and -not \emph{simple} or \emph{conditional} effects, as is the case when using R's default -\code{\link[stats:contrast]{stats::contr.treatment()}}). +In effects coding, unlike treatment/dummy coding +(\code{\link[stats:contrast]{stats::contr.treatment()}}), each contrast sums to 0. In regressions models, +this results in an intercept that represents the (unweighted) average of the +group means. In ANOVA settings, this also guarantees that lower order effects +represent \emph{main} effects (and not \emph{simple} or \emph{conditional} effects, as is +the case when using R's default \code{\link[stats:contrast]{stats::contr.treatment()}}). \cr\cr -Deviation coding (\code{contr.deviation}) is a type of effects coding. -With deviation coding, the coefficients for factor variables are interpreted -as the difference of each factor level from the base level -(this is the same interpretation as with treatment/dummy coding). -For example, for a factor \code{group} with levels "A", "B", and "C", with \code{contr.devation}, -the intercept represents the overall mean (average of the group means for the 3 groups), +Deviation coding (\code{contr.deviation}) is a type of effects coding. With +deviation coding, the coefficients for factor variables are interpreted as +the difference of each factor level from the base level (this is the same +interpretation as with treatment/dummy coding). For example, for a factor +\code{group} with levels "A", "B", and "C", with \code{contr.devation}, the intercept +represents the overall mean (average of the group means for the 3 groups), and the coefficients \code{groupB} and \code{groupC} represent the differences between the A group mean and the B and C group means, respectively. \cr\cr -Sum coding (\code{\link[stats:contrast]{stats::contr.sum()}}) is another type of effects coding. -With sum coding, the coefficients for factor variables are interpreted -as the difference of each factor level from \strong{the grand (across-groups) mean}. -For example, for a factor \code{group} with levels "A", "B", and "C", with \code{contr.sum}, -the intercept represents the overall mean (average of the group means for the 3 groups), -and the coefficients \code{group1} and \code{group2} represent the differences the +Sum coding (\code{\link[stats:contrast]{stats::contr.sum()}}) is another type of effects coding. With sum +coding, the coefficients for factor variables are interpreted as the +difference of each factor level from \strong{the grand (across-groups) mean}. For +example, for a factor \code{group} with levels "A", "B", and "C", with +\code{contr.sum}, the intercept represents the overall mean (average of the group +means for the 3 groups), and the coefficients \code{group1} and \code{group2} represent +the differences the \strong{A} and \strong{B} group means from the overall mean, respectively. } \examples{ -\dontrun{ +if (FALSE) { data("mtcars") mtcars <- data_modify(mtcars, cyl = factor(cyl)) @@ -78,7 +79,7 @@ solve(c.deviation) #> 8 -1.000 0.000 1.000 # 3rd level - 1st level ## With Interactions ----------------------------------------- -mtcars <- data_modify(mtcars, am = factor(am)) +mtcars <- data_modify(mtcars, am = C(am, contr = contr.deviation)) mtcars <- data_arrange(mtcars, select = c("cyl", "am")) mm <- unique(model.matrix(~ cyl * am, data = mtcars)) From dad5f2082f59248ed7ce76f7034d4a4d466627a9 Mon Sep 17 00:00:00 2001 From: Daniel Date: Tue, 29 Aug 2023 14:20:56 +0200 Subject: [PATCH 16/26] Fix invalid multibyte string (#452) * Fix invalid multibyte string * desc, news * fix * fix * add test * styler --- DESCRIPTION | 2 +- NEWS.md | 7 +++ R/contrs.R | 76 +++++++++++++-------------- R/data_read.R | 6 ++- R/remove_empty.R | 2 +- man/contr.deviation.Rd | 76 +++++++++++++-------------- tests/testthat/test-contr.deviation.R | 6 ++- tests/testthat/test-empty-dataframe.R | 13 +++++ 8 files changed, 107 insertions(+), 81 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 1c68c50f1..401e5ad9b 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Type: Package Package: datawizard Title: Easy Data Wrangling and Statistical Transformations -Version: 0.8.0.7 +Version: 0.8.0.8 Authors@R: c( person("Indrajeet", "Patil", , "patilindrajeet.science@gmail.com", role = "aut", comment = c(ORCID = "0000-0003-1995-6531", Twitter = "@patilindrajeets")), diff --git a/NEWS.md b/NEWS.md index 721ecd2ee..734cccd0d 100644 --- a/NEWS.md +++ b/NEWS.md @@ -15,6 +15,9 @@ CHANGES * `recode_into()` gains an `overwrite` argument to skip overwriting already recoded cases when multiple recode patterns apply to the same case. +* `data_read()` now passes the `encoding` argument to `data.table::fread()`. + This allows to read files with non-ASCII characters. + * `datawizard` moves from the GPL-3 license to the MIT license. BUG FIXES @@ -29,6 +32,10 @@ BUG FIXES naming arguments, like `grepl(pattern, x = a)`) were mistakenly seen as faulty syntax. +* Fixed issue in `empty_column()` for strings with invalid multibyte strings. + For such data frames or files, `empty_column()` or `data_read()` no longer + fails. + # datawizard 0.8.0 BREAKING CHANGES diff --git a/R/contrs.R b/R/contrs.R index e1d23f084..2e5638cea 100644 --- a/R/contrs.R +++ b/R/contrs.R @@ -34,52 +34,52 @@ #' #' @examples #' if (FALSE) { -#' data("mtcars") +#' data("mtcars") #' -#' mtcars <- data_modify(mtcars, cyl = factor(cyl)) +#' mtcars <- data_modify(mtcars, cyl = factor(cyl)) #' -#' c.treatment <- cbind(Intercept = 1, contrasts(mtcars$cyl)) -#' solve(c.treatment) -#' #> 4 6 8 -#' #> Intercept 1 0 0 # mean of the 1st level -#' #> 6 -1 1 0 # 2nd level - 1st level -#' #> 8 -1 0 1 # 3rd level - 1st level +#' c.treatment <- cbind(Intercept = 1, contrasts(mtcars$cyl)) +#' solve(c.treatment) +#' #> 4 6 8 +#' #> Intercept 1 0 0 # mean of the 1st level +#' #> 6 -1 1 0 # 2nd level - 1st level +#' #> 8 -1 0 1 # 3rd level - 1st level #' -#' contrasts(mtcars$cyl) <- contr.sum -#' c.sum <- cbind(Intercept = 1, contrasts(mtcars$cyl)) -#' solve(c.sum) -#' #> 4 6 8 -#' #> Intercept 0.333 0.333 0.333 # overall mean -#' #> 0.667 -0.333 -0.333 # deviation of 1st from overall mean -#' #> -0.333 0.667 -0.333 # deviation of 2nd from overall mean +#' contrasts(mtcars$cyl) <- contr.sum +#' c.sum <- cbind(Intercept = 1, contrasts(mtcars$cyl)) +#' solve(c.sum) +#' #> 4 6 8 +#' #> Intercept 0.333 0.333 0.333 # overall mean +#' #> 0.667 -0.333 -0.333 # deviation of 1st from overall mean +#' #> -0.333 0.667 -0.333 # deviation of 2nd from overall mean #' #' -#' contrasts(mtcars$cyl) <- contr.deviation -#' c.deviation <- cbind(Intercept = 1, contrasts(mtcars$cyl)) -#' solve(c.deviation) -#' #> 4 6 8 -#' #> Intercept 0.333 0.333 0.333 # overall mean -#' #> 6 -1.000 1.000 0.000 # 2nd level - 1st level -#' #> 8 -1.000 0.000 1.000 # 3rd level - 1st level +#' contrasts(mtcars$cyl) <- contr.deviation +#' c.deviation <- cbind(Intercept = 1, contrasts(mtcars$cyl)) +#' solve(c.deviation) +#' #> 4 6 8 +#' #> Intercept 0.333 0.333 0.333 # overall mean +#' #> 6 -1.000 1.000 0.000 # 2nd level - 1st level +#' #> 8 -1.000 0.000 1.000 # 3rd level - 1st level #' -#' ## With Interactions ----------------------------------------- -#' mtcars <- data_modify(mtcars, am = C(am, contr = contr.deviation)) -#' mtcars <- data_arrange(mtcars, select = c("cyl", "am")) +#' ## With Interactions ----------------------------------------- +#' mtcars <- data_modify(mtcars, am = C(am, contr = contr.deviation)) +#' mtcars <- data_arrange(mtcars, select = c("cyl", "am")) #' -#' mm <- unique(model.matrix(~ cyl * am, data = mtcars)) -#' rownames(mm) <- c( -#' "cyl4.am0", "cyl4.am1", "cyl6.am0", -#' "cyl6.am1", "cyl8.am0", "cyl8.am1" -#' ) +#' mm <- unique(model.matrix(~ cyl * am, data = mtcars)) +#' rownames(mm) <- c( +#' "cyl4.am0", "cyl4.am1", "cyl6.am0", +#' "cyl6.am1", "cyl8.am0", "cyl8.am1" +#' ) #' -#' solve(mm) -#' #> cyl4.am0 cyl4.am1 cyl6.am0 cyl6.am1 cyl8.am0 cyl8.am1 -#' #> (Intercept) 0.167 0.167 0.167 0.167 0.167 0.167 # overall mean -#' #> cyl6 -0.500 -0.500 0.500 0.500 0.000 0.000 # cyl MAIN eff: 2nd - 1st -#' #> cyl8 -0.500 -0.500 0.000 0.000 0.500 0.500 # cyl MAIN eff: 2nd - 1st -#' #> am1 -0.333 0.333 -0.333 0.333 -0.333 0.333 # am MAIN eff -#' #> cyl6:am1 1.000 -1.000 -1.000 1.000 0.000 0.000 -#' #> cyl8:am1 1.000 -1.000 0.000 0.000 -1.000 1.000 +#' solve(mm) +#' #> cyl4.am0 cyl4.am1 cyl6.am0 cyl6.am1 cyl8.am0 cyl8.am1 +#' #> (Intercept) 0.167 0.167 0.167 0.167 0.167 0.167 # overall mean +#' #> cyl6 -0.500 -0.500 0.500 0.500 0.000 0.000 # cyl MAIN eff: 2nd - 1st +#' #> cyl8 -0.500 -0.500 0.000 0.000 0.500 0.500 # cyl MAIN eff: 2nd - 1st +#' #> am1 -0.333 0.333 -0.333 0.333 -0.333 0.333 # am MAIN eff +#' #> cyl6:am1 1.000 -1.000 -1.000 1.000 0.000 0.000 +#' #> cyl8:am1 1.000 -1.000 0.000 0.000 -1.000 1.000 #' } #' #' @export diff --git a/R/data_read.R b/R/data_read.R index a4294e67b..2c3061570 100644 --- a/R/data_read.R +++ b/R/data_read.R @@ -271,7 +271,11 @@ data_read <- function(path, .read_text <- function(path, encoding, verbose, ...) { if (insight::check_if_installed("data.table", quietly = TRUE)) { - out <- data.table::fread(input = path, ...) + # set proper default encoding-value for fread + if (is.null(encoding)) { + encoding <- "unknown" + } + out <- data.table::fread(input = path, encoding = encoding, ...) class(out) <- "data.frame" return(out) } diff --git a/R/remove_empty.R b/R/remove_empty.R index 5828fc937..c7fd75423 100644 --- a/R/remove_empty.R +++ b/R/remove_empty.R @@ -63,7 +63,7 @@ empty_columns <- function(x) { } else { all_na <- colSums(is.na(x)) == nrow(x) all_empty <- vapply(x, function(i) { - (is.character(i) || is.factor(i)) && max(c(0, nchar(as.character(i))), na.rm = TRUE) == 0 + (is.character(i) || is.factor(i)) && !any(nzchar(as.character(i[!is.na(i)]))) }, FUN.VALUE = logical(1L)) which(all_na | all_empty) diff --git a/man/contr.deviation.Rd b/man/contr.deviation.Rd index 09b8b3279..fd5de7a4b 100644 --- a/man/contr.deviation.Rd +++ b/man/contr.deviation.Rd @@ -50,52 +50,52 @@ the differences the } \examples{ if (FALSE) { -data("mtcars") + data("mtcars") -mtcars <- data_modify(mtcars, cyl = factor(cyl)) + mtcars <- data_modify(mtcars, cyl = factor(cyl)) -c.treatment <- cbind(Intercept = 1, contrasts(mtcars$cyl)) -solve(c.treatment) -#> 4 6 8 -#> Intercept 1 0 0 # mean of the 1st level -#> 6 -1 1 0 # 2nd level - 1st level -#> 8 -1 0 1 # 3rd level - 1st level + c.treatment <- cbind(Intercept = 1, contrasts(mtcars$cyl)) + solve(c.treatment) + #> 4 6 8 + #> Intercept 1 0 0 # mean of the 1st level + #> 6 -1 1 0 # 2nd level - 1st level + #> 8 -1 0 1 # 3rd level - 1st level -contrasts(mtcars$cyl) <- contr.sum -c.sum <- cbind(Intercept = 1, contrasts(mtcars$cyl)) -solve(c.sum) -#> 4 6 8 -#> Intercept 0.333 0.333 0.333 # overall mean -#> 0.667 -0.333 -0.333 # deviation of 1st from overall mean -#> -0.333 0.667 -0.333 # deviation of 2nd from overall mean + contrasts(mtcars$cyl) <- contr.sum + c.sum <- cbind(Intercept = 1, contrasts(mtcars$cyl)) + solve(c.sum) + #> 4 6 8 + #> Intercept 0.333 0.333 0.333 # overall mean + #> 0.667 -0.333 -0.333 # deviation of 1st from overall mean + #> -0.333 0.667 -0.333 # deviation of 2nd from overall mean -contrasts(mtcars$cyl) <- contr.deviation -c.deviation <- cbind(Intercept = 1, contrasts(mtcars$cyl)) -solve(c.deviation) -#> 4 6 8 -#> Intercept 0.333 0.333 0.333 # overall mean -#> 6 -1.000 1.000 0.000 # 2nd level - 1st level -#> 8 -1.000 0.000 1.000 # 3rd level - 1st level + contrasts(mtcars$cyl) <- contr.deviation + c.deviation <- cbind(Intercept = 1, contrasts(mtcars$cyl)) + solve(c.deviation) + #> 4 6 8 + #> Intercept 0.333 0.333 0.333 # overall mean + #> 6 -1.000 1.000 0.000 # 2nd level - 1st level + #> 8 -1.000 0.000 1.000 # 3rd level - 1st level -## With Interactions ----------------------------------------- -mtcars <- data_modify(mtcars, am = C(am, contr = contr.deviation)) -mtcars <- data_arrange(mtcars, select = c("cyl", "am")) + ## With Interactions ----------------------------------------- + mtcars <- data_modify(mtcars, am = C(am, contr = contr.deviation)) + mtcars <- data_arrange(mtcars, select = c("cyl", "am")) -mm <- unique(model.matrix(~ cyl * am, data = mtcars)) -rownames(mm) <- c( - "cyl4.am0", "cyl4.am1", "cyl6.am0", - "cyl6.am1", "cyl8.am0", "cyl8.am1" -) + mm <- unique(model.matrix(~ cyl * am, data = mtcars)) + rownames(mm) <- c( + "cyl4.am0", "cyl4.am1", "cyl6.am0", + "cyl6.am1", "cyl8.am0", "cyl8.am1" + ) -solve(mm) -#> cyl4.am0 cyl4.am1 cyl6.am0 cyl6.am1 cyl8.am0 cyl8.am1 -#> (Intercept) 0.167 0.167 0.167 0.167 0.167 0.167 # overall mean -#> cyl6 -0.500 -0.500 0.500 0.500 0.000 0.000 # cyl MAIN eff: 2nd - 1st -#> cyl8 -0.500 -0.500 0.000 0.000 0.500 0.500 # cyl MAIN eff: 2nd - 1st -#> am1 -0.333 0.333 -0.333 0.333 -0.333 0.333 # am MAIN eff -#> cyl6:am1 1.000 -1.000 -1.000 1.000 0.000 0.000 -#> cyl8:am1 1.000 -1.000 0.000 0.000 -1.000 1.000 + solve(mm) + #> cyl4.am0 cyl4.am1 cyl6.am0 cyl6.am1 cyl8.am0 cyl8.am1 + #> (Intercept) 0.167 0.167 0.167 0.167 0.167 0.167 # overall mean + #> cyl6 -0.500 -0.500 0.500 0.500 0.000 0.000 # cyl MAIN eff: 2nd - 1st + #> cyl8 -0.500 -0.500 0.000 0.000 0.500 0.500 # cyl MAIN eff: 2nd - 1st + #> am1 -0.333 0.333 -0.333 0.333 -0.333 0.333 # am MAIN eff + #> cyl6:am1 1.000 -1.000 -1.000 1.000 0.000 0.000 + #> cyl8:am1 1.000 -1.000 0.000 0.000 -1.000 1.000 } } diff --git a/tests/testthat/test-contr.deviation.R b/tests/testthat/test-contr.deviation.R index 164c18837..0a1e55dda 100644 --- a/tests/testthat/test-contr.deviation.R +++ b/tests/testthat/test-contr.deviation.R @@ -21,8 +21,10 @@ test_that("contr.deviation | snapshot", { expect_snapshot(solve(c.deviation)) mm <- unique(model.matrix(~ cyl * am, data = mtcars)) - rownames(mm) <- c("cyl4.am0", "cyl4.am1", "cyl6.am0", - "cyl6.am1", "cyl8.am0", "cyl8.am1") + rownames(mm) <- c( + "cyl4.am0", "cyl4.am1", "cyl6.am0", + "cyl6.am1", "cyl8.am0", "cyl8.am1" + ) expect_snapshot(solve(mm)) }) diff --git a/tests/testthat/test-empty-dataframe.R b/tests/testthat/test-empty-dataframe.R index 56b8cd9cc..5ec33da38 100644 --- a/tests/testthat/test-empty-dataframe.R +++ b/tests/testthat/test-empty-dataframe.R @@ -59,3 +59,16 @@ test_that("empty_columns with only NA characters", { ) expect_identical(empty_columns(tmp), c(var2 = 2L)) }) + + +test_that("works with non-ascii chars", { + tmp <- data.frame( + a = c(1, 2, 3, NA, 5), + b = c("", NA, "", NA, ""), + c = c(NA, NA, NA, NA, NA), + d = c("test", "Se\x96ora", "works fine", "this too", "yeah"), + e = c("", "", "", "", ""), + stringsAsFactors = FALSE + ) + expect_identical(empty_columns(tmp), c(b = 2L, c = 3L, e = 5L)) +}) From 10599b29795fa93083d384d9cd5726f4fd84d80f Mon Sep 17 00:00:00 2001 From: Daniel Date: Wed, 30 Aug 2023 08:19:24 +0200 Subject: [PATCH 17/26] docs --- R/demean.R | 4 ++-- man/demean.Rd | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/R/demean.R b/R/demean.R index 3089e0b13..69e833a4d 100644 --- a/R/demean.R +++ b/R/demean.R @@ -28,13 +28,13 @@ #' @inheritParams center #' #' @return -#' #' A data frame with the group-/de-meaned variables, which get the suffix #' `"_between"` (for the group-meaned variable) and `"_within"` (for the #' de-meaned variable) by default. #' #' @seealso If grand-mean centering (instead of centering within-clusters) -#' is required, see [center()]. +#' is required, see [center()]. See [`performance::check_heterogeneity_bias()`] +#' to check for heterogeneity bias. #' #' @details #' diff --git a/man/demean.Rd b/man/demean.Rd index d1ed55aac..422c8d32e 100644 --- a/man/demean.Rd +++ b/man/demean.Rd @@ -255,5 +255,6 @@ fluctuation and change. New York: Routledge } \seealso{ If grand-mean centering (instead of centering within-clusters) -is required, see \code{\link[=center]{center()}}. +is required, see \code{\link[=center]{center()}}. See \code{\link[performance:check_heterogeneity_bias]{performance::check_heterogeneity_bias()}} +to check for heterogeneity bias. } From 877c5877334eb58a1a8d909cb6b5dd25d07f8a20 Mon Sep 17 00:00:00 2001 From: Daniel Date: Thu, 7 Sep 2023 16:08:18 +0200 Subject: [PATCH 18/26] Rename `rowmean_n()` to `row_means()` (#448) * Rename `rowmean_n()`? Fixes #447 * Update row_means.R * fix * fix * tests * docs * update pkgdown * fix tests * docs * Update NEWS.md Co-authored-by: Etienne Bacher <52219252+etiennebacher@users.noreply.github.com> * version bump --------- Co-authored-by: Etienne Bacher <52219252+etiennebacher@users.noreply.github.com> --- DESCRIPTION | 2 +- NAMESPACE | 2 +- NEWS.md | 6 +- R/row_means.R | 139 +++++++++++++++++++++++++++++++ R/rowmean_n.R | 101 ----------------------- _pkgdown.yaml | 2 +- man/row_means.Rd | 142 ++++++++++++++++++++++++++++++++ man/rowmean_n.Rd | 72 ---------------- tests/testthat/test-row_means.R | 27 ++++++ tests/testthat/test-rowmean_n.R | 26 ------ 10 files changed, 314 insertions(+), 205 deletions(-) create mode 100644 R/row_means.R delete mode 100644 R/rowmean_n.R create mode 100644 man/row_means.Rd delete mode 100644 man/rowmean_n.Rd create mode 100644 tests/testthat/test-row_means.R delete mode 100644 tests/testthat/test-rowmean_n.R diff --git a/DESCRIPTION b/DESCRIPTION index 401e5ad9b..e9c46fef5 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Type: Package Package: datawizard Title: Easy Data Wrangling and Statistical Transformations -Version: 0.8.0.8 +Version: 0.8.0.9 Authors@R: c( person("Indrajeet", "Patil", , "patilindrajeet.science@gmail.com", role = "aut", comment = c(ORCID = "0000-0003-1995-6531", Twitter = "@patilindrajeets")), diff --git a/NAMESPACE b/NAMESPACE index 30c064f62..a985af2f0 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -278,9 +278,9 @@ export(reshape_longer) export(reshape_wider) export(reverse) export(reverse_scale) +export(row_means) export(row_to_colnames) export(rowid_as_column) -export(rowmean_n) export(rownames_as_column) export(skewness) export(slide) diff --git a/NEWS.md b/NEWS.md index 734cccd0d..7e91322e7 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,10 +2,10 @@ NEW FUNCTIONS -* `contr.deviation()` for sum-deviation contrast coding of factors. +* `row_means()`, to compute row means, optionally only for the rows with at + least `min_valid` non-missing values. -* `rowmean_n()`, to compute row means if row contains at least `n` non-missing - values. +* `contr.deviation()` for sum-deviation contrast coding of factors. * `means_by_group()`, to compute mean values of variables, grouped by levels of specified factors. diff --git a/R/row_means.R b/R/row_means.R new file mode 100644 index 000000000..f252824b1 --- /dev/null +++ b/R/row_means.R @@ -0,0 +1,139 @@ +#' @title Row means (optionally with minimum amount of valid values) +#' @name row_means +#' @description This function is similar to the SPSS `MEAN.n` function and computes +#' row means from a data frame or matrix if at least `min_valid` values of a row are +#' valid (and not `NA`). +#' +#' @param data A data frame with at least two columns, where row means are applied. +#' @param min_valid Optional, a numeric value of length 1. May either be +#' - a numeric value that indicates the amount of valid values per row to +#' calculate the row mean; +#' - or a value between 0 and 1, indicating a proportion of valid values per +#' row to calculate the row mean (see 'Details'). +#' - `NULL` (default), in which all cases are considered. +#' +#' If a row's sum of valid values is less than `min_valid`, `NA` will be returned. +#' @param digits Numeric value indicating the number of decimal places to be +#' used for rounding mean values. Negative values are allowed (see 'Details'). +#' By default, `digits = NULL` and no rounding is used. +#' @param remove_na Logical, if `TRUE` (default), removes missing (`NA`) values +#' before calculating row means. Only applies if `min_valuid` is not specified. +#' @param verbose Toggle warnings. +#' @inheritParams find_columns +#' +#' @return A vector with row means for those rows with at least `n` valid values. +#' +#' @details Rounding to a negative number of `digits` means rounding to a power of +#' ten, for example `row_means(df, 3, digits = -2)` rounds to the nearest hundred. +#' For `min_valid`, if not `NULL`, `min_valid` must be a numeric value from `0` +#' to `ncol(data)`. If a row in the data frame has at least `min_valid` +#' non-missing values, the row mean is returned. If `min_valid` is a non-integer +#' value from 0 to 1, `min_valid` is considered to indicate the proportion of +#' required non-missing values per row. E.g., if `min_valid = 0.75`, a row must +#' have at least `ncol(data) * min_valid` non-missing values for the row mean +#' to be calculated. See 'Examples'. +#' +#' @examples +#' dat <- data.frame( +#' c1 = c(1, 2, NA, 4), +#' c2 = c(NA, 2, NA, 5), +#' c3 = c(NA, 4, NA, NA), +#' c4 = c(2, 3, 7, 8) +#' ) +#' +#' # default, all means are shown, if no NA values are present +#' row_means(dat) +#' +#' # remove all NA before computing row means +#' row_means(dat, remove_na = TRUE) +#' +#' # needs at least 4 non-missing values per row +#' row_means(dat, min_valid = 4) # 1 valid return value +#' +#' # needs at least 3 non-missing values per row +#' row_means(dat, min_valid = 3) # 2 valid return values +#' +#' # needs at least 2 non-missing values per row +#' row_means(dat, min_valid = 2) +#' +#' # needs at least 1 non-missing value per row, for two selected variables +#' row_means(dat, select = c("c1", "c3"), min_valid = 1) +#' +#' # needs at least 50% of non-missing values per row +#' row_means(dat, min_valid = 0.5) # 3 valid return values +#' +#' # needs at least 75% of non-missing values per row +#' row_means(dat, min_valid = 0.75) # 2 valid return values +#' +#' @export +row_means <- function(data, + select = NULL, + exclude = NULL, + min_valid = NULL, + digits = NULL, + ignore_case = FALSE, + regex = FALSE, + remove_na = FALSE, + verbose = TRUE) { + # evaluate arguments + select <- .select_nse(select, + data, + exclude, + ignore_case = ignore_case, + regex = regex, + verbose = verbose + ) + + if (is.null(select) || length(select) == 0) { + insight::format_error("No columns selected.") + } + + data <- .coerce_to_dataframe(data[select]) + + # n must be a numeric, non-missing value + if (!is.null(min_valid) && (all(is.na(min_valid)) || !is.numeric(min_valid) || length(min_valid) > 1)) { + insight::format_error("`min_valid` must be a numeric value of length 1.") + } + + # make sure we only have numeric values + numeric_columns <- vapply(data, is.numeric, TRUE) + if (!all(numeric_columns)) { + if (verbose) { + insight::format_alert("Only numeric columns are considered for calculation.") + } + data <- data[numeric_columns] + } + + # check if we have a data framme with at least two columns + if (ncol(data) < 2) { + insight::format_error("`data` must be a data frame with at least two numeric columns.") + } + + # proceed here if min_valid is not NULL + if (!is.null(min_valid)) { + # is 'min_valid' indicating a proportion? + decimals <- min_valid %% 1 + if (decimals != 0) { + min_valid <- round(ncol(data) * decimals) + } + + # min_valid may not be larger as df's amount of columns + if (ncol(data) < min_valid) { + insight::format_error("`min_valid` must be smaller or equal to number of columns in data frame.") + } + + # row means + to_na <- rowSums(is.na(data)) > ncol(data) - min_valid + out <- rowMeans(data, na.rm = TRUE) + out[to_na] <- NA + } else { + out <- rowMeans(data, na.rm = remove_na) + } + + # round, if requested + if (!is.null(digits) && !all(is.na(digits))) { + out <- round(out, digits = digits) + } + + out +} diff --git a/R/rowmean_n.R b/R/rowmean_n.R deleted file mode 100644 index ab47cf511..000000000 --- a/R/rowmean_n.R +++ /dev/null @@ -1,101 +0,0 @@ -#' @title Row means with minimum amount of valid values -#' @name rowmean_n -#' @description This function is similar to the SPSS `MEAN.n` function and computes -#' row means from a data frame or matrix if at least `n` values of a row are -#' valid (and not `NA`). -#' -#' @param data A data frame with at least two columns, where row means are applied. -#' @param n A numeric value of length 1. May either be -#' - a numeric value that indicates the amount of valid values per row to -#' calculate the row mean; -#' - or a value between 0 and 1, indicating a proportion of valid values per -#' row to calculate the row mean (see 'Details'). -#' -#' If a row's sum of valid values is less than `n`, `NA` will be returned. -#' @param digits Numeric value indicating the number of decimal places to be -#' used for rounding mean values. Negative values are allowed (see 'Details'). -#' By default, `digits = NULL` and no rounding is used. -#' @param verbose Toggle warnings. -#' -#' @return A vector with row means for those rows with at least `n` valid values. -#' -#' @details Rounding to a negative number of `digits` means rounding to a power of -#' ten, for example `rowmean_n(df, 3, digits = -2)` rounds to the nearest hundred. -#' For `n`, must be a numeric value from `0` to `ncol(data)`. If a row in the -#' data frame has at least `n` non-missing values, the row mean is returned. If -#' `n` is a non-integer value from 0 to 1, `n` is considered to indicate the -#' proportion of required non-missing values per row. E.g., if `n = 0.75`, a -#' row must have at least `ncol(data) * n` non-missing values for the row mean -#' to be calculated. See 'Examples'. -#' -#' @examples -#' dat <- data.frame( -#' c1 = c(1, 2, NA, 4), -#' c2 = c(NA, 2, NA, 5), -#' c3 = c(NA, 4, NA, NA), -#' c4 = c(2, 3, 7, 8) -#' ) -#' -#' # needs at least 4 non-missing values per row -#' rowmean_n(dat, 4) # 1 valid return value -#' -#' # needs at least 3 non-missing values per row -#' rowmean_n(dat, 3) # 2 valid return values -#' -#' # needs at least 2 non-missing values per row -#' rowmean_n(dat, 2) -#' -#' # needs at least 1 non-missing value per row -#' rowmean_n(dat, 1) # all means are shown -#' -#' # needs at least 50% of non-missing values per row -#' rowmean_n(dat, 0.5) # 3 valid return values -#' -#' # needs at least 75% of non-missing values per row -#' rowmean_n(dat, 0.75) # 2 valid return values -#' -#' @export -rowmean_n <- function(data, n, digits = NULL, verbose = TRUE) { - data <- .coerce_to_dataframe(data) - - # n must be a numeric, non-missing value - if (is.null(n) || all(is.na(n)) || !is.numeric(n) || length(n) > 1) { - insight::format_error("`n` must be a numeric value of length 1.") - } - - # make sure we only have numeric values - numeric_columns <- vapply(data, is.numeric, TRUE) - if (!all(numeric_columns)) { - if (verbose) { - insight::format_alert("Only numeric columns are considered for calculation.") - } - data <- data[numeric_columns] - } - - # check if we have a data framme with at least two columns - if (ncol(data) < 2) { - insight::format_error("`data` must be a data frame with at least two numeric columns.") - } - - # is 'n' indicating a proportion? - decimals <- n %% 1 - if (decimals != 0) { - n <- round(ncol(data) * decimals) - } - - # n may not be larger as df's amount of columns - if (ncol(data) < n) { - insight::format_error("`n` must be smaller or equal to number of columns in data frame.") - } - - # row means - to_na <- rowSums(is.na(data)) > ncol(data) - n - out <- rowMeans(data, na.rm = TRUE) - out[to_na] <- NA - - # round, if requested - if (!is.null(digits) && !all(is.na(digits))) { - out <- round(out, digits = digits) - } - out -} diff --git a/_pkgdown.yaml b/_pkgdown.yaml index 7e0aa5cb4..db2ebfeae 100644 --- a/_pkgdown.yaml +++ b/_pkgdown.yaml @@ -68,8 +68,8 @@ reference: - kurtosis - smoothness - skewness + - row_means - weighted_mean - - rowmean_n - mean_sd - title: Convert and Replace Data diff --git a/man/row_means.Rd b/man/row_means.Rd new file mode 100644 index 000000000..6e4a7774b --- /dev/null +++ b/man/row_means.Rd @@ -0,0 +1,142 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/row_means.R +\name{row_means} +\alias{row_means} +\title{Row means (optionally with minimum amount of valid values)} +\usage{ +row_means( + data, + select = NULL, + exclude = NULL, + min_valid = NULL, + digits = NULL, + ignore_case = FALSE, + regex = FALSE, + remove_na = FALSE, + verbose = TRUE +) +} +\arguments{ +\item{data}{A data frame with at least two columns, where row means are applied.} + +\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"}), or a character +vector of variable names (e.g., \code{c("col1", "col2", "col3")}), +\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")}. +\item or 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{find_columns(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{min_valid}{Optional, a numeric value of length 1. May either be +\itemize{ +\item a numeric value that indicates the amount of valid values per row to +calculate the row mean; +\item or a value between 0 and 1, indicating a proportion of valid values per +row to calculate the row mean (see 'Details'). +\item \code{NULL} (default), in which all cases are considered. +} + +If a row's sum of valid values is less than \code{min_valid}, \code{NA} will be returned.} + +\item{digits}{Numeric value indicating the number of decimal places to be +used for rounding mean values. Negative values are allowed (see 'Details'). +By default, \code{digits = NULL} and no rounding is used.} + +\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{remove_na}{Logical, if \code{TRUE} (default), removes missing (\code{NA}) values +before calculating row means. Only applies if \code{min_valuid} is not specified.} + +\item{verbose}{Toggle warnings.} +} +\value{ +A vector with row means for those rows with at least \code{n} valid values. +} +\description{ +This function is similar to the SPSS \code{MEAN.n} function and computes +row means from a data frame or matrix if at least \code{min_valid} values of a row are +valid (and not \code{NA}). +} +\details{ +Rounding to a negative number of \code{digits} means rounding to a power of +ten, for example \code{row_means(df, 3, digits = -2)} rounds to the nearest hundred. +For \code{min_valid}, if not \code{NULL}, \code{min_valid} must be a numeric value from \code{0} +to \code{ncol(data)}. If a row in the data frame has at least \code{min_valid} +non-missing values, the row mean is returned. If \code{min_valid} is a non-integer +value from 0 to 1, \code{min_valid} is considered to indicate the proportion of +required non-missing values per row. E.g., if \code{min_valid = 0.75}, a row must +have at least \code{ncol(data) * min_valid} non-missing values for the row mean +to be calculated. See 'Examples'. +} +\examples{ +dat <- data.frame( + c1 = c(1, 2, NA, 4), + c2 = c(NA, 2, NA, 5), + c3 = c(NA, 4, NA, NA), + c4 = c(2, 3, 7, 8) +) + +# default, all means are shown, if no NA values are present +row_means(dat) + +# remove all NA before computing row means +row_means(dat, remove_na = TRUE) + +# needs at least 4 non-missing values per row +row_means(dat, min_valid = 4) # 1 valid return value + +# needs at least 3 non-missing values per row +row_means(dat, min_valid = 3) # 2 valid return values + +# needs at least 2 non-missing values per row +row_means(dat, min_valid = 2) + +# needs at least 1 non-missing value per row, for two selected variables +row_means(dat, select = c("c1", "c3"), min_valid = 1) + +# needs at least 50\% of non-missing values per row +row_means(dat, min_valid = 0.5) # 3 valid return values + +# needs at least 75\% of non-missing values per row +row_means(dat, min_valid = 0.75) # 2 valid return values + +} diff --git a/man/rowmean_n.Rd b/man/rowmean_n.Rd deleted file mode 100644 index df340eed3..000000000 --- a/man/rowmean_n.Rd +++ /dev/null @@ -1,72 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/rowmean_n.R -\name{rowmean_n} -\alias{rowmean_n} -\title{Row means with minimum amount of valid values} -\usage{ -rowmean_n(data, n, digits = NULL, verbose = TRUE) -} -\arguments{ -\item{data}{A data frame with at least two columns, where row means are applied.} - -\item{n}{A numeric value of length 1. May either be -\itemize{ -\item a numeric value that indicates the amount of valid values per row to -calculate the row mean; -\item or a value between 0 and 1, indicating a proportion of valid values per -row to calculate the row mean (see 'Details'). -} - -If a row's sum of valid values is less than \code{n}, \code{NA} will be returned.} - -\item{digits}{Numeric value indicating the number of decimal places to be -used for rounding mean values. Negative values are allowed (see 'Details'). -By default, \code{digits = NULL} and no rounding is used.} - -\item{verbose}{Toggle warnings.} -} -\value{ -A vector with row means for those rows with at least \code{n} valid values. -} -\description{ -This function is similar to the SPSS \code{MEAN.n} function and computes -row means from a data frame or matrix if at least \code{n} values of a row are -valid (and not \code{NA}). -} -\details{ -Rounding to a negative number of \code{digits} means rounding to a power of -ten, for example \code{rowmean_n(df, 3, digits = -2)} rounds to the nearest hundred. -For \code{n}, must be a numeric value from \code{0} to \code{ncol(data)}. If a row in the -data frame has at least \code{n} non-missing values, the row mean is returned. If -\code{n} is a non-integer value from 0 to 1, \code{n} is considered to indicate the -proportion of required non-missing values per row. E.g., if \code{n = 0.75}, a -row must have at least \code{ncol(data) * n} non-missing values for the row mean -to be calculated. See 'Examples'. -} -\examples{ -dat <- data.frame( - c1 = c(1, 2, NA, 4), - c2 = c(NA, 2, NA, 5), - c3 = c(NA, 4, NA, NA), - c4 = c(2, 3, 7, 8) -) - -# needs at least 4 non-missing values per row -rowmean_n(dat, 4) # 1 valid return value - -# needs at least 3 non-missing values per row -rowmean_n(dat, 3) # 2 valid return values - -# needs at least 2 non-missing values per row -rowmean_n(dat, 2) - -# needs at least 1 non-missing value per row -rowmean_n(dat, 1) # all means are shown - -# needs at least 50\% of non-missing values per row -rowmean_n(dat, 0.5) # 3 valid return values - -# needs at least 75\% of non-missing values per row -rowmean_n(dat, 0.75) # 2 valid return values - -} diff --git a/tests/testthat/test-row_means.R b/tests/testthat/test-row_means.R new file mode 100644 index 000000000..8d0504c69 --- /dev/null +++ b/tests/testthat/test-row_means.R @@ -0,0 +1,27 @@ +test_that("row_means", { + d_mn <- data.frame( + c1 = c(1, 2, NA, 4), + c2 = c(NA, 2, NA, 5), + c3 = c(NA, 4, NA, NA), + c4 = c(2, 3, 7, 8) + ) + expect_equal(row_means(d_mn, min_valid = 4), c(NA, 2.75, NA, NA), tolerance = 1e-3) + expect_equal(row_means(d_mn, min_valid = 3), c(NA, 2.75, NA, 5.66667), tolerance = 1e-3) + expect_equal(row_means(d_mn, min_valid = 2), c(1.5, 2.75, NA, 5.66667), tolerance = 1e-3) + expect_equal(row_means(d_mn, min_valid = 1), c(1.5, 2.75, 7, 5.66667), tolerance = 1e-3) + expect_equal(row_means(d_mn, min_valid = 0.5), c(1.5, 2.75, NA, 5.66667), tolerance = 1e-3) + expect_equal(row_means(d_mn, min_valid = 0.75), c(NA, 2.75, NA, 5.66667), tolerance = 1e-3) + expect_equal(row_means(d_mn, min_valid = 2, digits = 1), c(1.5, 2.8, NA, 5.7), tolerance = 1e-1) + expect_message(row_means(iris), regex = "Only numeric") + expect_equal(row_means(iris, verbose = FALSE), rowMeans(iris[, 1:4]), tolerance = 1e-3, ignore_attr = TRUE) +}) + +test_that("row_means, errors or messages", { + data(iris) + expect_error(expect_warning(row_means(iris, select = "abc")), regex = "No columns") + expect_error(row_means(iris[1], min_valid = 1), regex = "two numeric") + expect_error(row_means(iris, min_valid = 1:4), regex = "numeric value") + expect_error(row_means(iris, min_valid = "a"), regex = "numeric value") + expect_message(row_means(iris[1:3, ], min_valid = 3), regex = "Only numeric") + expect_silent(row_means(iris[1:3, ], min_valid = 3, verbose = FALSE)) +}) diff --git a/tests/testthat/test-rowmean_n.R b/tests/testthat/test-rowmean_n.R deleted file mode 100644 index a17996ff6..000000000 --- a/tests/testthat/test-rowmean_n.R +++ /dev/null @@ -1,26 +0,0 @@ -test_that("rowmean_n", { - d_mn <- data.frame( - c1 = c(1, 2, NA, 4), - c2 = c(NA, 2, NA, 5), - c3 = c(NA, 4, NA, NA), - c4 = c(2, 3, 7, 8) - ) - expect_equal(rowmean_n(d_mn, 4), c(NA, 2.75, NA, NA), tolerance = 1e-3) - expect_equal(rowmean_n(d_mn, 3), c(NA, 2.75, NA, 5.66667), tolerance = 1e-3) - expect_equal(rowmean_n(d_mn, 2), c(1.5, 2.75, NA, 5.66667), tolerance = 1e-3) - expect_equal(rowmean_n(d_mn, 1), c(1.5, 2.75, 7, 5.66667), tolerance = 1e-3) - expect_equal(rowmean_n(d_mn, 0.5), c(1.5, 2.75, NA, 5.66667), tolerance = 1e-3) - expect_equal(rowmean_n(d_mn, 0.75), c(NA, 2.75, NA, 5.66667), tolerance = 1e-3) - expect_equal(rowmean_n(d_mn, 2, digits = 1), c(1.5, 2.8, NA, 5.7), tolerance = 1e-1) -}) - -test_that("rowmean_n, errors or messages", { - data(iris) - expect_error(rowmean_n(5, n = 1), regex = "`data` must be") - expect_error(rowmean_n(iris[1], n = 1), regex = "two numeric") - expect_error(rowmean_n(iris, n = NULL), regex = "numeric value") - expect_error(rowmean_n(iris, n = 1:4), regex = "numeric value") - expect_error(rowmean_n(iris, n = "a"), regex = "numeric value") - expect_message(rowmean_n(iris[1:3, ], n = 3), regex = "Only numeric") - expect_silent(rowmean_n(iris[1:3, ], n = 3, verbose = FALSE)) -}) From 1b3b82541538ecbf0a57039875f189ccfca88bc0 Mon Sep 17 00:00:00 2001 From: Daniel Date: Thu, 7 Sep 2023 20:20:29 +0200 Subject: [PATCH 19/26] fix issues with NA values in recodes (#455) * fix issues with NA values in recodes * add reserve_na attr, add tests * add comments * version bump * Update test-recode_into.R * scoping issue * rename objects in tests, maybe fixes random test order --- DESCRIPTION | 2 +- NEWS.md | 6 +++ R/recode_into.r | 26 ++++++++++++- man/recode_into.Rd | 14 ++++++- tests/testthat/test-recode_into.R | 64 ++++++++++++++++++++++++++++++- 5 files changed, 107 insertions(+), 5 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index e9c46fef5..76d6967bc 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Type: Package Package: datawizard Title: Easy Data Wrangling and Statistical Transformations -Version: 0.8.0.9 +Version: 0.8.0.10 Authors@R: c( person("Indrajeet", "Patil", , "patilindrajeet.science@gmail.com", role = "aut", comment = c(ORCID = "0000-0003-1995-6531", Twitter = "@patilindrajeets")), diff --git a/NEWS.md b/NEWS.md index 7e91322e7..295570ec4 100644 --- a/NEWS.md +++ b/NEWS.md @@ -15,6 +15,9 @@ CHANGES * `recode_into()` gains an `overwrite` argument to skip overwriting already recoded cases when multiple recode patterns apply to the same case. +* `recode_into()` gains an `preserve_na` argument to preserve `NA` values + when recoding. + * `data_read()` now passes the `encoding` argument to `data.table::fread()`. This allows to read files with non-ASCII characters. @@ -28,6 +31,9 @@ BUG FIXES * Fixed issue in `recode_into()` with probably wrong case number printed in the warning when several recode patterns match to one case. +* Fixed issue in `recode_into()` when original data contained `NA` values and + `NA` was not included in the recode pattern. + * Fixed issue in `data_filter()` where functions containing a `=` (e.g. when naming arguments, like `grepl(pattern, x = a)`) were mistakenly seen as faulty syntax. diff --git a/R/recode_into.r b/R/recode_into.r index 8a382fbe1..b93dbe5d9 100644 --- a/R/recode_into.r +++ b/R/recode_into.r @@ -20,6 +20,10 @@ #' recode patterns. If `FALSE`, former recoded cases will not be altered by later #' recode patterns that would apply to those cases again. A warning message is #' printed to alert such situations and to avoid unintentional recodings. +#' @param preserve_na Logical, if `TRUE` (default) and `default` is not `NA`, +#' missing values in the original variable will be set back to `NA` in the +#' recoded variable (unless overwritten by other recode patterns). If `FALSE`, +#' missing values in the original variable will be recoded to `default`. #' @param verbose Toggle warnings. #' #' @return A vector with recoded values. @@ -73,7 +77,12 @@ #' default = 0 #' ) #' @export -recode_into <- function(..., data = NULL, default = NA, overwrite = TRUE, verbose = TRUE) { +recode_into <- function(..., + data = NULL, + default = NA, + overwrite = TRUE, + preserve_na = TRUE, + verbose = TRUE) { dots <- list(...) # get length of vector, so we know the length of the output vector @@ -135,6 +144,12 @@ recode_into <- function(..., data = NULL, default = NA, overwrite = TRUE, verbos index <- with(data, eval(dots[[i]][[2]])) value <- with(data, eval(dots[[i]][[3]])) } + # remember missing values, so we can add back later + missing_index <- is.na(index) + # make sure index has no missing values. when we have missing values in + # original expression, these are considered as "no match" and set to FALSE + # we handle NA value later and thus want to remove them from "index" now + index[is.na(index)] <- FALSE # overwriting values? do more recode-patterns match the same case? if (is.na(default)) { already_exists <- !is.na(out[index]) @@ -144,7 +159,7 @@ recode_into <- function(..., data = NULL, default = NA, overwrite = TRUE, verbos # save indices of overwritten cases overwritten_cases <- which(index)[already_exists] # tell user... - if (any(already_exists) && verbose) { + if (any(already_exists, na.rm = TRUE) && verbose) { if (overwrite) { msg <- paste( "Several recode patterns apply to the same cases.", @@ -164,7 +179,14 @@ recode_into <- function(..., data = NULL, default = NA, overwrite = TRUE, verbos if (!overwrite) { index[overwritten_cases] <- FALSE } + # write new values into output vector out[index] <- value + # set back missing values + if (any(missing_index) && !is.na(default) && preserve_na) { + # but only where we still have default values + # we don't want to overwrite already recoded values with NA + out[missing_index & out == default] <- NA + } } out diff --git a/man/recode_into.Rd b/man/recode_into.Rd index 064d72f6c..b3e164131 100644 --- a/man/recode_into.Rd +++ b/man/recode_into.Rd @@ -4,7 +4,14 @@ \alias{recode_into} \title{Recode values from one or more variables into a new variable} \usage{ -recode_into(..., data = NULL, default = NA, overwrite = TRUE, verbose = TRUE) +recode_into( + ..., + data = NULL, + default = NA, + overwrite = TRUE, + preserve_na = TRUE, + verbose = TRUE +) } \arguments{ \item{...}{A sequence of two-sided formulas, where the left hand side (LHS) @@ -25,6 +32,11 @@ recode patterns. If \code{FALSE}, former recoded cases will not be altered by la recode patterns that would apply to those cases again. A warning message is printed to alert such situations and to avoid unintentional recodings.} +\item{preserve_na}{Logical, if \code{TRUE} (default) and \code{default} is not \code{NA}, +missing values in the original variable will be set back to \code{NA} in the +recoded variable (unless overwritten by other recode patterns). If \code{FALSE}, +missing values in the original variable will be recoded to \code{default}.} + \item{verbose}{Toggle warnings.} } \value{ diff --git a/tests/testthat/test-recode_into.R b/tests/testthat/test-recode_into.R index ab5c7908b..df7cf60b2 100644 --- a/tests/testthat/test-recode_into.R +++ b/tests/testthat/test-recode_into.R @@ -170,7 +170,7 @@ test_that("recode_into, check differen input length", { ) }) -test_that("recode_into, check differen input length", { +test_that("recode_into, check different input length", { x <- 1:5 y <- c(5, 2, 3, 1, 4) expect_warning( @@ -184,3 +184,65 @@ test_that("recode_into, check differen input length", { regexp = "Several recode patterns" ) }) + +test_that("recode_into, make sure recode works with missing in original variable", { + data(mtcars) + mtcars$mpg[c(3, 10, 12, 15, 16)] <- NA + mtcars$cyl[c(2, 15, 16)] <- NA + d_recode_na <<- as.data.frame(mtcars) + out1_recoded_na <- recode_into( + d_recode_na$mpg > 20 & d_recode_na$cyl == 6 ~ 1, + d_recode_na$mpg <= 20 ~ 2, + d_recode_na$cyl == 4 ~ 3, + default = 0 + ) + out2_recoded_na <- recode_into( + d_recode_na$mpg > 20 & d_recode_na$cyl == 6 ~ 1, + d_recode_na$mpg <= 20 ~ 2, + default = 0 + ) + out3_recoded_na <- recode_into( + d_recode_na$mpg > 20 & d_recode_na$cyl == 6 ~ 1, + d_recode_na$mpg <= 20 ~ 2, + d_recode_na$cyl == 4 ~ 3, + default = 0, + preserve_na = FALSE + ) + out4_recoded_na <- recode_into( + d_recode_na$mpg > 20 & d_recode_na$cyl == 6 ~ 1, + d_recode_na$mpg <= 20 ~ 2, + default = 0, + preserve_na = FALSE + ) + # one NA in mpg is overwritten by valid value from cyl, total 5 NA + expect_identical( + out1_recoded_na, + c( + 1, NA, 3, 1, 2, 2, 2, 3, 3, NA, 2, NA, 2, 2, NA, NA, 2, 3, + 3, 3, 3, 2, 2, 2, 2, 3, 3, 3, 2, 2, 2, 3 + ) + ) + # total 6 NA + expect_identical( + out2_recoded_na, + c( + 1, NA, NA, 1, 2, 2, 2, 0, 0, NA, 2, NA, 2, 2, NA, NA, 2, 0, + 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2, 0 + ) + ) + # NA is preserved, set to default if not overwritten by other recodes + expect_identical( + out3_recoded_na, + c( + 1, 0, 3, 1, 2, 2, 2, 3, 3, 0, 2, 0, 2, 2, 0, 0, 2, 3, 3, 3, + 3, 2, 2, 2, 2, 3, 3, 3, 2, 2, 2, 3 + ) + ) + expect_identical( + out4_recoded_na, + c( + 1, 0, 0, 1, 2, 2, 2, 0, 0, 0, 2, 0, 2, 2, 0, 0, 2, 0, 0, 0, + 0, 2, 2, 2, 2, 0, 0, 0, 2, 2, 2, 0 + ) + ) +}) From 35c4f13d86269d44f152fb0b447d7e158855f79e Mon Sep 17 00:00:00 2001 From: Daniel Date: Thu, 7 Sep 2023 20:39:42 +0200 Subject: [PATCH 20/26] improve handling --- R/recode_into.r | 57 ++++++++++++++++++++++++++----- man/recode_into.Rd | 38 ++++++++++++++++++--- tests/testthat/test-recode_into.R | 38 ++++++++++++++------- 3 files changed, 106 insertions(+), 27 deletions(-) diff --git a/R/recode_into.r b/R/recode_into.r index b93dbe5d9..a33f03eb7 100644 --- a/R/recode_into.r +++ b/R/recode_into.r @@ -20,10 +20,13 @@ #' recode patterns. If `FALSE`, former recoded cases will not be altered by later #' recode patterns that would apply to those cases again. A warning message is #' printed to alert such situations and to avoid unintentional recodings. -#' @param preserve_na Logical, if `TRUE` (default) and `default` is not `NA`, -#' missing values in the original variable will be set back to `NA` in the -#' recoded variable (unless overwritten by other recode patterns). If `FALSE`, -#' missing values in the original variable will be recoded to `default`. +#' @param preserve_na Logical, if `TRUE` and `default` is not `NA`, missing +#' values in the original variable will be set back to `NA` in the recoded +#' variable (unless overwritten by other recode patterns). If `FALSE`, missing +#' values in the original variable will be recoded to `default`. The latter +#' behaviour prevents unintentional overwriting of missing values with `default`, +#' which means that you won't find valid values where the original data only +#' had missing values. See 'Examples'. #' @param verbose Toggle warnings. #' #' @return A vector with recoded values. @@ -76,12 +79,37 @@ #' data = d, #' default = 0 #' ) +#' +#' # handling of missing values +#' d <- data.frame( +#' x = c(1, NA, 2, NA, 3, 4), +#' y = c(1, 11, 3, NA, 5, 6) +#' ) +#' # first NA in x is overwritten by valid value from y +#' # we have no known value for second NA in x and y, +#' # thus we get one NA in the result +#' recode_into( +#' x <= 3 ~ 1, +#' y > 5 ~ 2, +#' data = d, +#' default = 0, +#' preserve_na = TRUE +#' ) +#' # first NA in x is overwritten by valid value from y +#' # default value is used for second NA +#' recode_into( +#' x <= 3 ~ 1, +#' y > 5 ~ 2, +#' data = d, +#' default = 0, +#' preserve_na = FALSE +#' ) #' @export recode_into <- function(..., data = NULL, default = NA, overwrite = TRUE, - preserve_na = TRUE, + preserve_na = FALSE, verbose = TRUE) { dots <- list(...) @@ -133,6 +161,9 @@ recode_into <- function(..., ) } + # indicator to show message when replacing NA by default + # needed to show message only once + overwrite_NA_msg <- TRUE # iterate all expressions for (i in seq_len(n_params)) { @@ -182,10 +213,18 @@ recode_into <- function(..., # write new values into output vector out[index] <- value # set back missing values - if (any(missing_index) && !is.na(default) && preserve_na) { - # but only where we still have default values - # we don't want to overwrite already recoded values with NA - out[missing_index & out == default] <- NA + if (any(missing_index) && !is.na(default)) { + if (preserve_na) { + # but only where we still have default values + # we don't want to overwrite already recoded values with NA + out[missing_index & out == default] <- NA + } else if (overwrite_NA_msg && verbose) { + # don't show msg again + overwrite_NA_msg <- FALSE + insight::format_alert( + "Missing values in original variable are overwritten by default value. If you want to preserve missing values, set `preserve_na = TRUE`." + ) + } } } diff --git a/man/recode_into.Rd b/man/recode_into.Rd index b3e164131..d8d0a337d 100644 --- a/man/recode_into.Rd +++ b/man/recode_into.Rd @@ -9,7 +9,7 @@ recode_into( data = NULL, default = NA, overwrite = TRUE, - preserve_na = TRUE, + preserve_na = FALSE, verbose = TRUE ) } @@ -32,10 +32,13 @@ recode patterns. If \code{FALSE}, former recoded cases will not be altered by la recode patterns that would apply to those cases again. A warning message is printed to alert such situations and to avoid unintentional recodings.} -\item{preserve_na}{Logical, if \code{TRUE} (default) and \code{default} is not \code{NA}, -missing values in the original variable will be set back to \code{NA} in the -recoded variable (unless overwritten by other recode patterns). If \code{FALSE}, -missing values in the original variable will be recoded to \code{default}.} +\item{preserve_na}{Logical, if \code{TRUE} and \code{default} is not \code{NA}, missing +values in the original variable will be set back to \code{NA} in the recoded +variable (unless overwritten by other recode patterns). If \code{FALSE}, missing +values in the original variable will be recoded to \code{default}. The latter +behaviour prevents unintentional overwriting of missing values with \code{default}, +which means that you won't find valid values where the original data only +had missing values. See 'Examples'.} \item{verbose}{Toggle warnings.} } @@ -95,4 +98,29 @@ recode_into( data = d, default = 0 ) + +# handling of missing values +d <- data.frame( + x = c(1, NA, 2, NA, 3, 4), + y = c(1, 11, 3, NA, 5, 6) +) +# first NA in x is overwritten by valid value from y +# we have no known value for second NA in x and y, +# thus we get one NA in the result +recode_into( + x <= 3 ~ 1, + y > 5 ~ 2, + data = d, + default = 0, + preserve_na = TRUE +) +# first NA in x is overwritten by valid value from y +# default value is used for second NA +recode_into( + x <= 3 ~ 1, + y > 5 ~ 2, + data = d, + default = 0, + preserve_na = FALSE +) } diff --git a/tests/testthat/test-recode_into.R b/tests/testthat/test-recode_into.R index df7cf60b2..90fabcd2f 100644 --- a/tests/testthat/test-recode_into.R +++ b/tests/testthat/test-recode_into.R @@ -194,25 +194,37 @@ test_that("recode_into, make sure recode works with missing in original variable d_recode_na$mpg > 20 & d_recode_na$cyl == 6 ~ 1, d_recode_na$mpg <= 20 ~ 2, d_recode_na$cyl == 4 ~ 3, - default = 0 + default = 0, + preserve_na = TRUE ) out2_recoded_na <- recode_into( d_recode_na$mpg > 20 & d_recode_na$cyl == 6 ~ 1, d_recode_na$mpg <= 20 ~ 2, - default = 0 - ) - out3_recoded_na <- recode_into( - d_recode_na$mpg > 20 & d_recode_na$cyl == 6 ~ 1, - d_recode_na$mpg <= 20 ~ 2, - d_recode_na$cyl == 4 ~ 3, default = 0, - preserve_na = FALSE + preserve_na = TRUE ) - out4_recoded_na <- recode_into( - d_recode_na$mpg > 20 & d_recode_na$cyl == 6 ~ 1, - d_recode_na$mpg <= 20 ~ 2, - default = 0, - preserve_na = FALSE + expect_message( + { + out3_recoded_na <- recode_into( + d_recode_na$mpg > 20 & d_recode_na$cyl == 6 ~ 1, + d_recode_na$mpg <= 20 ~ 2, + d_recode_na$cyl == 4 ~ 3, + default = 0, + preserve_na = FALSE + ) + }, + regex = "Missing values in original variable" + ) + expect_message( + { + out4_recoded_na <- recode_into( + d_recode_na$mpg > 20 & d_recode_na$cyl == 6 ~ 1, + d_recode_na$mpg <= 20 ~ 2, + default = 0, + preserve_na = FALSE + ) + }, + regex = "Missing values in original variable" ) # one NA in mpg is overwritten by valid value from cyl, total 5 NA expect_identical( From 2acaef27141b1371213a707a6f28f678671d0224 Mon Sep 17 00:00:00 2001 From: Daniel Date: Thu, 7 Sep 2023 21:48:31 +0200 Subject: [PATCH 21/26] docs --- R/recode_into.r | 8 ++++---- man/recode_into.Rd | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/R/recode_into.r b/R/recode_into.r index a33f03eb7..fc369a62a 100644 --- a/R/recode_into.r +++ b/R/recode_into.r @@ -23,10 +23,10 @@ #' @param preserve_na Logical, if `TRUE` and `default` is not `NA`, missing #' values in the original variable will be set back to `NA` in the recoded #' variable (unless overwritten by other recode patterns). If `FALSE`, missing -#' values in the original variable will be recoded to `default`. The latter -#' behaviour prevents unintentional overwriting of missing values with `default`, -#' which means that you won't find valid values where the original data only -#' had missing values. See 'Examples'. +#' values in the original variable will be recoded to `default`. Setting +#' `preserve_na = TRUE` prevents unintentional overwriting of missing values +#' with `default`, which means that you won't find valid values where the +#' original data only had missing values. See 'Examples'. #' @param verbose Toggle warnings. #' #' @return A vector with recoded values. diff --git a/man/recode_into.Rd b/man/recode_into.Rd index d8d0a337d..b0acc7c9f 100644 --- a/man/recode_into.Rd +++ b/man/recode_into.Rd @@ -35,10 +35,10 @@ printed to alert such situations and to avoid unintentional recodings.} \item{preserve_na}{Logical, if \code{TRUE} and \code{default} is not \code{NA}, missing values in the original variable will be set back to \code{NA} in the recoded variable (unless overwritten by other recode patterns). If \code{FALSE}, missing -values in the original variable will be recoded to \code{default}. The latter -behaviour prevents unintentional overwriting of missing values with \code{default}, -which means that you won't find valid values where the original data only -had missing values. See 'Examples'.} +values in the original variable will be recoded to \code{default}. Setting +\code{preserve_na = TRUE} prevents unintentional overwriting of missing values +with \code{default}, which means that you won't find valid values where the +original data only had missing values. See 'Examples'.} \item{verbose}{Toggle warnings.} } From fbd4430d7143e186b14952f6e3da7d2c8e55e4df Mon Sep 17 00:00:00 2001 From: Daniel Date: Fri, 8 Sep 2023 13:06:10 +0200 Subject: [PATCH 22/26] fix labels_to_levels (#456) * fix labels_to_levels * fix * lintr * lintr * add comments --- DESCRIPTION | 2 +- NEWS.md | 3 +++ R/utils_labels.R | 16 +++++++++++++++- tests/testthat/test-labels_to_levels.R | 24 ++++++++++++++++++++++-- 4 files changed, 41 insertions(+), 4 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 76d6967bc..9fed6f068 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Type: Package Package: datawizard Title: Easy Data Wrangling and Statistical Transformations -Version: 0.8.0.10 +Version: 0.8.0.11 Authors@R: c( person("Indrajeet", "Patil", , "patilindrajeet.science@gmail.com", role = "aut", comment = c(ORCID = "0000-0003-1995-6531", Twitter = "@patilindrajeets")), diff --git a/NEWS.md b/NEWS.md index 295570ec4..160c0fae2 100644 --- a/NEWS.md +++ b/NEWS.md @@ -25,6 +25,9 @@ CHANGES BUG FIXES +* Fixed issue in `labels_to_levels()` when values of labels were not in sorted + order and values were not sequentially numbered. + * Fixed issues in `data_write()` when writing labelled data into SPSS format and vectors were of different type as value labels. diff --git a/R/utils_labels.R b/R/utils_labels.R index 54b1c46fd..67b3ecc6a 100644 --- a/R/utils_labels.R +++ b/R/utils_labels.R @@ -46,7 +46,21 @@ "Not all factor levels had a matching value label. Non-matching levels were preserved." ) } - levels(x)[levels_in_labs] <- names(value_labels[labs_in_levels]) + if (length(value_labels) == length(levels_in_labs)) { + # when length of value_labels and levels_in_labs is identical, we can simply + # replace the levels with the value labels. This makes sure than levels or + # value labels, which are not sorted or not sequentially numbered, match. + # Example: + # x <- c(5, 5, 1, 3, 1, 7) + # attr(x, "labels") <- c(no = 7, yes = 1, maybe = 3, `don't know` = 5) + # to_factor(x, labels_to_levels = TRUE) + levels(x)[levels_in_labs] <- names(value_labels) + } else { + # else, we need to select only those value labels that have a matching level + # (in labs_in_levels). This is required when not all values that have labels + # appear in the data. + levels(x)[levels_in_labs] <- names(value_labels[labs_in_levels]) + } attr(x, "labels") <- NULL x diff --git a/tests/testthat/test-labels_to_levels.R b/tests/testthat/test-labels_to_levels.R index 518dac70e..55105acfe 100644 --- a/tests/testthat/test-labels_to_levels.R +++ b/tests/testthat/test-labels_to_levels.R @@ -8,13 +8,13 @@ test_that("labels_to_levels, numeric", { test_that("labels_to_levels, factor", { data(efc) x <- as.factor(efc$c172code) - attr(x, "labels") <- c("low" = 1, "mid" = 2, "high" = 3) + attr(x, "labels") <- c(low = 1, mid = 2, high = 3) x <- labels_to_levels(x) expect_identical(levels(x), c("low", "mid", "high")) expect_equal(table(x), table(efc$c172code), ignore_attr = TRUE) x <- as.ordered(efc$c172code) - attr(x, "labels") <- c("low" = 1, "mid" = 2, "high" = 3) + attr(x, "labels") <- c(low = 1, mid = 2, high = 3) x <- labels_to_levels(x) expect_identical(levels(x), c("low", "mid", "high")) expect_s3_class(x, "ordered") @@ -40,3 +40,23 @@ test_that("labels_to_levels, factor, data frame", { ) expect_identical(sum(vapply(efc, is.factor, TRUE)), 1L) }) + +test_that("labels_to_levels, factor, with random value numbers (no sequential order)", { + x <- c(5, 5, 1, 3, 1, 7) + attr(x, "labels") <- c(no = 7, yes = 1, maybe = 3, `don't know` = 5) + out <- to_factor(x, labels_to_levels = TRUE) + expect_identical(as.character(out), c("don't know", "don't know", "yes", "maybe", "yes", "no")) + expect_identical(levels(out), c("yes", "maybe", "don't know", "no")) + + x <- c(4, 4, 1, 2, 1, 3) + attr(x, "labels") <- c(a = 1, b = 2, c = 3, d = 4) + out <- to_factor(x, labels_to_levels = TRUE) + expect_identical(as.character(out), c("d", "d", "a", "b", "a", "c")) + expect_identical(levels(out), c("a", "b", "c", "d")) + + x <- c(4, 4, 1, 2, 1, 3) + attr(x, "labels") <- c(d = 1, c = 2, b = 3, a = 4) + out <- to_factor(x, labels_to_levels = TRUE) + expect_identical(as.character(out), c("a", "a", "d", "c", "d", "b")) + expect_identical(levels(out), c("d", "c", "b", "a")) +}) From bcbc115cd36979e839637ab7068fa69d1dfea655 Mon Sep 17 00:00:00 2001 From: Daniel Date: Fri, 8 Sep 2023 16:51:10 +0200 Subject: [PATCH 23/26] Need more fixing (#457) * fix labels_to_levels * fix * lintr * lintr * add comments * still not working for all edge cases * fix * namespace * fix * desc * styler --- DESCRIPTION | 2 +- R/utils_labels.R | 26 ++++----- tests/testthat/test-labels_to_levels.R | 73 ++++++++++++++++++++++++++ 3 files changed, 85 insertions(+), 16 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 9fed6f068..c062db49e 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -1,7 +1,7 @@ Type: Package Package: datawizard Title: Easy Data Wrangling and Statistical Transformations -Version: 0.8.0.11 +Version: 0.8.0.12 Authors@R: c( person("Indrajeet", "Patil", , "patilindrajeet.science@gmail.com", role = "aut", comment = c(ORCID = "0000-0003-1995-6531", Twitter = "@patilindrajeets")), diff --git a/R/utils_labels.R b/R/utils_labels.R index 67b3ecc6a..a7f4fa2c3 100644 --- a/R/utils_labels.R +++ b/R/utils_labels.R @@ -46,21 +46,17 @@ "Not all factor levels had a matching value label. Non-matching levels were preserved." ) } - if (length(value_labels) == length(levels_in_labs)) { - # when length of value_labels and levels_in_labs is identical, we can simply - # replace the levels with the value labels. This makes sure than levels or - # value labels, which are not sorted or not sequentially numbered, match. - # Example: - # x <- c(5, 5, 1, 3, 1, 7) - # attr(x, "labels") <- c(no = 7, yes = 1, maybe = 3, `don't know` = 5) - # to_factor(x, labels_to_levels = TRUE) - levels(x)[levels_in_labs] <- names(value_labels) - } else { - # else, we need to select only those value labels that have a matching level - # (in labs_in_levels). This is required when not all values that have labels - # appear in the data. - levels(x)[levels_in_labs] <- names(value_labels[labs_in_levels]) - } + # we need to find out which levels have no labelled value + missing_levels <- levels(x)[!levels(x) %in% value_labels] + + # and we need to remove those value labels that don't have a matching level + value_labels <- value_labels[value_labels %in% levels(x)] + + # for levels that have no label, we just keep the original factor level + value_labels <- c(value_labels, stats::setNames(missing_levels, missing_levels)) + + # now we can add back levels + levels(x) <- names(value_labels)[order(as.numeric(value_labels))] attr(x, "labels") <- NULL x diff --git a/tests/testthat/test-labels_to_levels.R b/tests/testthat/test-labels_to_levels.R index 55105acfe..866154c8f 100644 --- a/tests/testthat/test-labels_to_levels.R +++ b/tests/testthat/test-labels_to_levels.R @@ -59,4 +59,77 @@ test_that("labels_to_levels, factor, with random value numbers (no sequential or out <- to_factor(x, labels_to_levels = TRUE) expect_identical(as.character(out), c("a", "a", "d", "c", "d", "b")) expect_identical(levels(out), c("d", "c", "b", "a")) + + x <- c(5, 5, 1, 3, 1, 7) + attr(x, "labels") <- c(no = 7, yes = 1, maybe = 3, `don't know` = 5) + out <- to_factor(x, labels_to_levels = TRUE) + expect_identical( + out, + structure( + c(3L, 3L, 1L, 2L, 1L, 4L), + levels = c("yes", "maybe", "don't know", "no"), + class = "factor" + ) + ) + expect_identical( + as.character(out), + c("don't know", "don't know", "yes", "maybe", "yes", "no") + ) + + x <- c(5, 5, 1, 3, 1, 7, 4) + attr(x, "labels") <- c(no = 7, yes = 1, maybe = 3, `don't know` = 5) + expect_message( + { + out <- to_factor(x, labels_to_levels = TRUE) + }, + regex = "Not all factor levels" + ) + expect_identical( + out, + structure( + c(4L, 4L, 1L, 2L, 1L, 5L, 3L), + levels = c("yes", "maybe", "4", "don't know", "no"), + class = "factor" + ) + ) + expect_identical( + as.character(out), + c("don't know", "don't know", "yes", "maybe", "yes", "no", "4") + ) + + x <- c(5, 5, 1, 3, 1, 7) + attr(x, "labels") <- c(no = 7, yes = 1, maybe = 4, `don't know` = 5) + expect_message({ + out <- to_factor(x, labels_to_levels = TRUE) + }) + expect_identical( + out, + structure( + c(3L, 3L, 1L, 2L, 1L, 4L), + levels = c("yes", "3", "don't know", "no"), + class = "factor" + ) + ) + expect_identical( + as.character(out), + c("don't know", "don't know", "yes", "3", "yes", "no") + ) + + x <- c(5, 5, 1, 3, 1, 7, 6) + attr(x, "labels") <- c(no = 7, yes = 1, maybe = 4, `don't know` = 5) + expect_message({ + out <- to_factor(x, labels_to_levels = TRUE) + }) + expect_identical( + out, + structure( + c(3L, 3L, 1L, 2L, 1L, 5L, 4L), + levels = c("yes", "3", "don't know", "6", "no"), + class = "factor" + ) + ) + expect_identical( + as.character(out), + c("don't know", "don't know", "yes", "3", "yes", "no", "6") + ) }) From 6e09435dc978454436faf0d33230d1d69b1ce8ee Mon Sep 17 00:00:00 2001 From: Daniel Date: Fri, 8 Sep 2023 17:15:53 +0200 Subject: [PATCH 24/26] rename 1 --- R/{data_peek.r => _data_peek.R} | 0 R/{data_write.r => _data_write.R} | 0 R/{recode_into.r => _recode_into.R} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename R/{data_peek.r => _data_peek.R} (100%) rename R/{data_write.r => _data_write.R} (100%) rename R/{recode_into.r => _recode_into.R} (100%) diff --git a/R/data_peek.r b/R/_data_peek.R similarity index 100% rename from R/data_peek.r rename to R/_data_peek.R diff --git a/R/data_write.r b/R/_data_write.R similarity index 100% rename from R/data_write.r rename to R/_data_write.R diff --git a/R/recode_into.r b/R/_recode_into.R similarity index 100% rename from R/recode_into.r rename to R/_recode_into.R From ae7df24b9dce7207e361dd7906fc241743fb90f1 Mon Sep 17 00:00:00 2001 From: Daniel Date: Fri, 8 Sep 2023 17:16:14 +0200 Subject: [PATCH 25/26] rename 2 --- R/{_data_peek.R => data_peek.R} | 0 R/{_data_write.R => data_write.R} | 0 R/{_recode_into.R => recode_into.R} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename R/{_data_peek.R => data_peek.R} (100%) rename R/{_data_write.R => data_write.R} (100%) rename R/{_recode_into.R => recode_into.R} (100%) diff --git a/R/_data_peek.R b/R/data_peek.R similarity index 100% rename from R/_data_peek.R rename to R/data_peek.R diff --git a/R/_data_write.R b/R/data_write.R similarity index 100% rename from R/_data_write.R rename to R/data_write.R diff --git a/R/_recode_into.R b/R/recode_into.R similarity index 100% rename from R/_recode_into.R rename to R/recode_into.R From ad96b50122f3297e0edd9664a6305c30d2a6b18e Mon Sep 17 00:00:00 2001 From: Etienne Bacher <52219252+etiennebacher@users.noreply.github.com> Date: Tue, 12 Sep 2023 10:01:47 +0000 Subject: [PATCH 26/26] `unnormalize()` with grouped data (#415) * working example * fix small bug * some comments * fix order of attributes * refactor unnormalize for groups * test error message * fix test * fix args of unnormalize * clean some lints * start same for `unstandardize()` [skip ci] * typo * styler * fix unstandardize() for groups * remove former test * ensure that both functions return a grouped dataframe * lintr, styler * lintr, styler, minor doc * add some extra checks * fix * unnormalize: from warning to error * bump news --------- Co-authored-by: Daniel --- NAMESPACE | 1 + NEWS.md | 5 + R/normalize.R | 24 +++- R/standardize.R | 37 ++++-- R/unnormalize.R | 105 +++++++++++++++++- R/unstandardize.R | 79 ++++++++++++- man/describe_distribution.Rd | 13 +-- man/normalize.Rd | 11 ++ tests/testthat/_snaps/means_by_group.md | 2 +- .../testthat/_snaps/windows/means_by_group.md | 2 +- tests/testthat/test-standardize-data.R | 75 ++++++++++++- tests/testthat/test-unnormalize.R | 75 ++++++++++++- 12 files changed, 391 insertions(+), 38 deletions(-) diff --git a/NAMESPACE b/NAMESPACE index a985af2f0..6b842fe03 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -182,6 +182,7 @@ S3method(to_numeric,logical) S3method(to_numeric,numeric) S3method(unnormalize,data.frame) S3method(unnormalize,default) +S3method(unnormalize,grouped_df) S3method(unnormalize,numeric) S3method(unstandardize,array) S3method(unstandardize,character) diff --git a/NEWS.md b/NEWS.md index 160c0fae2..48b598ab1 100644 --- a/NEWS.md +++ b/NEWS.md @@ -23,6 +23,11 @@ CHANGES * `datawizard` moves from the GPL-3 license to the MIT license. +* `unnormalize()` and `unstandardize()` now work with grouped data (#415). + +* `unnormalize()` now errors instead of emitting a warning if it doesn't have the + necessary info (#415). + BUG FIXES * Fixed issue in `labels_to_levels()` when values of labels were not in sorted diff --git a/R/normalize.R b/R/normalize.R index c8f63c67f..d8efb6c80 100644 --- a/R/normalize.R +++ b/R/normalize.R @@ -214,9 +214,15 @@ normalize.grouped_df <- function(x, } x <- as.data.frame(x) - for (rows in grps) { - x[rows, ] <- normalize( - x[rows, , drop = FALSE], + + # create column(s) to store dw_transformer attributes + for (i in select) { + info$groups[[paste0("attr_", i)]] <- rep(NA, length(grps)) + } + + for (rows in seq_along(grps)) { + tmp <- normalize( + x[grps[[rows]], , drop = FALSE], select = select, exclude = exclude, include_bounds = include_bounds, @@ -225,9 +231,21 @@ normalize.grouped_df <- function(x, add_transform_class = FALSE, ... ) + + # store dw_transformer_attributes + for (i in select) { + info$groups[rows, paste0("attr_", i)][[1]] <- list(unlist(attributes(tmp[[i]]))) + } + + x[grps[[rows]], ] <- tmp } + + # last column of "groups" attributes must be called ".rows" + info$groups <- data_relocate(info$groups, ".rows", after = -1) + # set back class, so data frame still works with dplyr attributes(x) <- utils::modifyList(info, attributes(x)) + class(x) <- c("grouped_df", class(x)) x } diff --git a/R/standardize.R b/R/standardize.R index ab4c6065b..0c88722b6 100644 --- a/R/standardize.R +++ b/R/standardize.R @@ -205,9 +205,9 @@ standardize.matrix <- function(x, ...) { x_out <- do.call(cbind, xz) dimnames(x_out) <- dimnames(x) - attr(x_out, "center") <- sapply(xz, attr, "center") - attr(x_out, "scale") <- sapply(xz, attr, "scale") - attr(x_out, "robust") <- sapply(xz, attr, "robust")[1] + attr(x_out, "center") <- vapply(xz, attr, "center", FUN.VALUE = numeric(1L)) + attr(x_out, "scale") <- vapply(xz, attr, "scale", FUN.VALUE = numeric(1L)) + attr(x_out, "robust") <- vapply(xz, attr, "robust", FUN.VALUE = logical(1L))[1] class(x_out) <- c("dw_transformer", class(x_out)) x_out @@ -300,9 +300,12 @@ standardize.data.frame <- function(x, ) } - - attr(x, "center") <- sapply(x[args$select], function(z) attributes(z)$center) - attr(x, "scale") <- sapply(x[args$select], function(z) attributes(z)$scale) + attr(x, "center") <- unlist(lapply(x[args$select], function(z) { + attributes(z)$center + })) + attr(x, "scale") <- unlist(lapply(x[args$select], function(z) { + attributes(z)$scale + })) attr(x, "robust") <- robust x } @@ -341,9 +344,14 @@ standardize.grouped_df <- function(x, reference, weights, keep_factors = force ) - for (rows in args$grps) { - args$x[rows, ] <- standardize( - args$x[rows, , drop = FALSE], + # create column(s) to store dw_transformer attributes + for (i in select) { + args$info$groups[[paste0("attr_", i)]] <- rep(NA, length(args$grps)) + } + + for (rows in seq_along(args$grps)) { + tmp <- standardize( + args$x[args$grps[[rows]], , drop = FALSE], select = args$select, exclude = NULL, robust = robust, @@ -358,7 +366,18 @@ standardize.grouped_df <- function(x, add_transform_class = FALSE, ... ) + + # store dw_transformer_attributes + for (i in select) { + args$info$groups[rows, paste0("attr_", i)][[1]] <- list(unlist(attributes(tmp[[i]]))) + } + + args$x[args$grps[[rows]], ] <- tmp } + + # last column of "groups" attributes must be called ".rows" + args$info$groups <- data_relocate(args$info$groups, ".rows", after = -1) + # set back class, so data frame still works with dplyr attributes(args$x) <- args$info args$x diff --git a/R/unnormalize.R b/R/unnormalize.R index 640978b1c..ea41dcd61 100644 --- a/R/unnormalize.R +++ b/R/unnormalize.R @@ -17,14 +17,32 @@ unnormalize.default <- function(x, ...) { #' @export unnormalize.numeric <- function(x, verbose = TRUE, ...) { ## TODO implement algorithm include_bounds = FALSE - include_bounds <- attr(x, "include_bounds") - min_value <- attr(x, "min_value") - range_difference <- attr(x, "range_difference") - to_range <- attr(x, "to_range") + + # if function called from the "grouped_df" method, we use the dw_transformer + # attributes that were recovered in the "grouped_df" method + + dots <- match.call(expand.dots = FALSE)[["..."]] + grp_attr_dw <- eval(dots$grp_attr_dw, envir = parent.frame(1L)) + + if (!is.null(grp_attr_dw)) { + names(grp_attr_dw) <- gsub(".*\\.", "", names(grp_attr_dw)) + include_bounds <- grp_attr_dw["include_bounds"] + min_value <- grp_attr_dw["min_value"] + range_difference <- grp_attr_dw["range_difference"] + to_range <- grp_attr_dw["to_range"] + if (is.na(to_range)) { + to_range <- NULL + } + } else { + include_bounds <- attr(x, "include_bounds") + min_value <- attr(x, "min_value") + range_difference <- attr(x, "range_difference") + to_range <- attr(x, "to_range") + } if (is.null(min_value) || is.null(range_difference)) { if (verbose) { - insight::format_warning("Can't unnormalize variable. Information about range and/or minimum value is missing.") + insight::format_error("Can't unnormalize variable. Information about range and/or minimum value is missing.") } return(x) } @@ -54,7 +72,82 @@ unnormalize.data.frame <- function(x, regex = regex, verbose = verbose ) - x[select] <- lapply(x[select], unnormalize, verbose = verbose) + # if function called from the "grouped_df" method, we use the dw_transformer + # attributes that were recovered in the "grouped_df" method + + dots <- match.call(expand.dots = FALSE)[["..."]] + + if (!is.null(dots$grp_attr_dw)) { + grp_attr_dw <- eval(dots$grp_attr_dw, envir = parent.frame(1L)) + } else { + grp_attr_dw <- NULL + } + + for (i in select) { + var_attr <- grep(paste0("^attr\\_", i, "\\."), names(grp_attr_dw)) + attrs <- grp_attr_dw[var_attr] + x[[i]] <- unnormalize(x[[i]], verbose = verbose, grp_attr_dw = attrs) + } + + x +} + +#' @rdname normalize +#' @export +unnormalize.grouped_df <- function(x, + select = NULL, + exclude = NULL, + ignore_case = FALSE, + regex = FALSE, + verbose = TRUE, + ...) { + # evaluate select/exclude, may be select-helpers + select <- .select_nse(select, + x, + exclude, + ignore_case, + regex = regex, + remove_group_var = TRUE, + verbose = verbose + ) + + info <- attributes(x) + # works only for dplyr >= 0.8.0 + grps <- attr(x, "groups", exact = TRUE)[[".rows"]] + + x <- as.data.frame(x) + + for (i in select) { + if (is.null(info$groups[[paste0("attr_", i)]])) { + insight::format_error( + paste( + "Couldn't retrieve the necessary information to unnormalize", + text_concatenate(i, enclose = "`") + ) + ) + } + } + for (rows in seq_along(grps)) { + # get the dw_transformer attributes for this group + raw_attrs <- unlist(info$groups[rows, startsWith(names(info$groups), "attr")]) + if (length(select) == 1L) { + names(raw_attrs) <- paste0("attr_", select, ".", names(raw_attrs)) + } + + tmp <- unnormalize( + x[grps[[rows]], , drop = FALSE], + select = select, + exclude = exclude, + ignore_case = ignore_case, + regex = regex, + verbose = verbose, + grp_attr_dw = raw_attrs + ) + x[grps[[rows]], ] <- tmp + } + # set back class, so data frame still works with dplyr + attributes(x) <- utils::modifyList(info, attributes(x)) + class(x) <- c("grouped_df", class(x)) x } diff --git a/R/unstandardize.R b/R/unstandardize.R index 0aea9ec06..d3714d4df 100644 --- a/R/unstandardize.R +++ b/R/unstandardize.R @@ -70,7 +70,23 @@ unstandardize.data.frame <- function(x, verbose = verbose ) - if (!is.null(reference)) { + dots <- match.call(expand.dots = FALSE)[["..."]] + + if (!is.null(dots$grp_attr_dw)) { + grp_attr_dw <- eval(dots$grp_attr_dw, envir = parent.frame(1L)) + } else { + grp_attr_dw <- NULL + } + + if (!is.null(grp_attr_dw)) { + center <- vapply(cols, function(x) { + grp_attr_dw[grep(paste0("^attr\\_", x, "\\.center"), names(grp_attr_dw))] + }, FUN.VALUE = numeric(1L)) + scale <- vapply(cols, function(x) { + grp_attr_dw[grep(paste0("^attr\\_", x, "\\.scale"), names(grp_attr_dw))] + }, FUN.VALUE = numeric(1L)) + i <- vapply(x[, cols, drop = FALSE], is.numeric, FUN.VALUE = logical(1L)) + } else if (!is.null(reference)) { i <- vapply(x[, cols, drop = FALSE], is.numeric, FUN.VALUE = logical(1L)) i <- i[i] reference <- reference[names(i)] @@ -143,8 +159,67 @@ unstandardize.grouped_df <- function(x, reference = NULL, robust = FALSE, two_sd = FALSE, + select = NULL, + exclude = NULL, + ignore_case = FALSE, + regex = FALSE, + verbose = TRUE, ...) { - insight::format_error("Cannot (yet) unstandardize a `grouped_df`.") + # evaluate select/exclude, may be select-helpers + select <- .select_nse(select, + x, + exclude, + ignore_case, + regex = regex, + remove_group_var = TRUE, + verbose = verbose + ) + + info <- attributes(x) + + # works only for dplyr >= 0.8.0 + grps <- attr(x, "groups", exact = TRUE)[[".rows"]] + + x <- as.data.frame(x) + + for (i in select) { + if (is.null(info$groups[[paste0("attr_", i)]])) { + insight::format_error( + paste( + "Couldn't retrieve the necessary information to unstandardize", + text_concatenate(i, enclose = "`") + ) + ) + } + } + + for (rows in seq_along(grps)) { + # get the dw_transformer attributes for this group + raw_attrs <- unlist(info$groups[rows, startsWith(names(info$groups), "attr")]) + if (length(select) == 1L) { + names(raw_attrs) <- paste0("attr_", select, ".", names(raw_attrs)) + } + + tmp <- unstandardise( + x[grps[[rows]], , drop = FALSE], + center = center, + scale = scale, + reference = reference, + robust = robust, + two_sd = two_sd, + select = select, + exclude = exclude, + ignore_case = ignore_case, + regex = regex, + verbose = verbose, + grp_attr_dw = raw_attrs + ) + x[grps[[rows]], ] <- tmp + } + # set back class, so data frame still works with dplyr + attributes(x) <- utils::modifyList(info, attributes(x)) + class(x) <- c("grouped_df", class(x)) + x } #' @export diff --git a/man/describe_distribution.Rd b/man/describe_distribution.Rd index fd229567d..a23069eea 100644 --- a/man/describe_distribution.Rd +++ b/man/describe_distribution.Rd @@ -50,14 +50,9 @@ describe_distribution(x, ...) \item{...}{Additional arguments to be passed to or from methods.} -\item{centrality}{The point-estimates (centrality indices) to compute. Character -(vector) or list with one or more of these options: \code{"median"}, \code{"mean"}, \code{"MAP"} -(see \code{\link[bayestestR:map_estimate]{map_estimate()}}), \code{"trimmed"} (which is just \code{mean(x, trim = threshold)}), -\code{"mode"} or \code{"all"}.} +\item{centrality}{The point-estimates (centrality indices) to compute. Character (vector) or list with one or more of these options: \code{"median"}, \code{"mean"}, \code{"MAP"} or \code{"all"}.} -\item{dispersion}{Logical, if \code{TRUE}, computes indices of dispersion related -to the estimate(s) (\code{SD} and \code{MAD} for \code{mean} and \code{median}, respectively). -Dispersion is not available for \code{"MAP"} or \code{"mode"} centrality indices.} +\item{dispersion}{Logical, if \code{TRUE}, computes indices of dispersion related to the estimate(s) (\code{SD} and \code{MAD} for \code{mean} and \code{median}, respectively).} \item{iqr}{Logical, if \code{TRUE}, the interquartile range is calculated (based on \code{\link[stats:IQR]{stats::IQR()}}, using \code{type = 6}).} @@ -76,9 +71,7 @@ the first centrality index (which is typically the median).} \item{iterations}{The number of bootstrap replicates for computing confidence intervals. Only applies when \code{ci} is not \code{NULL}.} -\item{threshold}{For \code{centrality = "trimmed"} (i.e. trimmed mean), indicates -the fraction (0 to 0.5) of observations to be trimmed from each end of the -vector before the mean is computed.} +\item{threshold}{For \code{centrality = "trimmed"} (i.e. trimmed mean), indicates the fraction (0 to 0.5) of observations to be trimmed from each end of the vector before the mean is computed.} \item{verbose}{Toggle warnings and messages.} diff --git a/man/normalize.Rd b/man/normalize.Rd index b797bf513..646e5b5ec 100644 --- a/man/normalize.Rd +++ b/man/normalize.Rd @@ -7,6 +7,7 @@ \alias{unnormalize} \alias{unnormalize.numeric} \alias{unnormalize.data.frame} +\alias{unnormalize.grouped_df} \title{Normalize numeric variable to 0-1 range} \usage{ normalize(x, ...) @@ -38,6 +39,16 @@ unnormalize(x, ...) verbose = TRUE, ... ) + +\method{unnormalize}{grouped_df}( + x, + select = NULL, + exclude = NULL, + ignore_case = FALSE, + regex = FALSE, + verbose = TRUE, + ... +) } \arguments{ \item{x}{A numeric vector, (grouped) data frame, or matrix. See 'Details'.} diff --git a/tests/testthat/_snaps/means_by_group.md b/tests/testthat/_snaps/means_by_group.md index 78a43d8b4..e49faebc3 100644 --- a/tests/testthat/_snaps/means_by_group.md +++ b/tests/testthat/_snaps/means_by_group.md @@ -1,4 +1,4 @@ -# meany_by_group +# mean_by_group Code means_by_group(efc, "c12hour", "e42dep") diff --git a/tests/testthat/_snaps/windows/means_by_group.md b/tests/testthat/_snaps/windows/means_by_group.md index 198069da9..6f80d7e25 100644 --- a/tests/testthat/_snaps/windows/means_by_group.md +++ b/tests/testthat/_snaps/windows/means_by_group.md @@ -1,4 +1,4 @@ -# meany_by_group, weighted +# mean_by_group, weighted Code means_by_group(efc, "c12hour", "e42dep", weights = "weight") diff --git a/tests/testthat/test-standardize-data.R b/tests/testthat/test-standardize-data.R index bf409a4bc..4056ee0b9 100644 --- a/tests/testthat/test-standardize-data.R +++ b/tests/testthat/test-standardize-data.R @@ -212,10 +212,6 @@ test_that("unstandardize, data frame", { x <- standardize(iris, robust = TRUE, two_sd = TRUE) rez <- unstandardize(x, robust = TRUE, two_sd = TRUE) expect_equal(rez, iris, tolerance = 0.1, ignore_attr = TRUE) - - d <- poorman::group_by(mtcars, am) - x <- standardize(d) - expect_error(unstandardize(x)) }) test_that("un/standardize, matrix", { @@ -281,3 +277,74 @@ test_that("standardize when only providing one of center/scale", { (x - mean(x)) / 1.5 ) }) + + +# grouped data + +test_that("unstandardize: grouped data", { + skip_if_not_installed("poorman") + + # 1 group, 1 standardized var + stand <- poorman::group_by(mtcars, cyl) + stand <- standardize(stand, "mpg") + unstand <- unstandardize(stand, select = "mpg") + expect_identical( + poorman::ungroup(unstand), + mtcars, + ignore_attr = TRUE + ) + + expect_s3_class(unstand, "grouped_df") + + # 2 groups, 1 standardized var + set.seed(123) + test <- iris + test$grp <- sample(c("A", "B"), nrow(test), replace = TRUE) + stand <- poorman::group_by(test, Species, grp) + stand <- standardize(stand, "Sepal.Length") + expect_identical( + poorman::ungroup(unstandardize(stand, select = "Sepal.Length")), + test + ) + + # 2 groups, 2 standardized vars + set.seed(123) + test <- iris + test$grp <- sample(c("A", "B"), nrow(test), replace = TRUE) + stand <- poorman::group_by(test, Species, grp) + stand <- standardize(stand, c("Sepal.Length", "Petal.Length")) + expect_identical( + poorman::ungroup(unstandardize(stand, select = c("Sepal.Length", "Petal.Length"))), + test + ) + + expect_s3_class(unstand, "grouped_df") + + # can't recover attributes + stand <- poorman::group_by(iris, Species) + stand <- standardize(stand, "Sepal.Length") + attr(stand, "groups") <- NULL + + expect_error( + unstandardize(stand, "Sepal.Length"), + regexp = "Couldn't retrieve the necessary information" + ) + + # normalize applied on grouped data but unstandardize applied on ungrouped data + stand <- poorman::group_by(mtcars, cyl) + stand <- standardize(stand, "mpg") + stand <- poorman::ungroup(stand) + + expect_error( + unstandardize(stand, "mpg"), + regexp = "must provide the arguments" + ) + + # standardize applied on grouped data but unstandardize applied different grouped + # data + stand <- poorman::group_by(stand, am) + expect_error( + unstandardize(stand, "mpg"), + regexp = "Couldn't retrieve the necessary" + ) +}) diff --git a/tests/testthat/test-unnormalize.R b/tests/testthat/test-unnormalize.R index b5793d850..c4c71050c 100644 --- a/tests/testthat/test-unnormalize.R +++ b/tests/testthat/test-unnormalize.R @@ -5,7 +5,10 @@ test_that("unnormalize work as expected", { c(0, 1, 5, -5, -2), ignore_attr = TRUE ) - expect_warning(expect_equal(unnormalize(c(0, 1, 5, -5, -2)), c(0, 1, 5, -5, -2), ignore_attr = TRUE)) + expect_error( + unnormalize(c(0, 1, 5, -5, -2)), + "Can't unnormalize variable" + ) }) test_that("unnormalize error if not supported", { @@ -54,8 +57,76 @@ test_that("unnormalize and unstandardized x 4", { # select helpers ------------------------------ test_that("unnormalize regex", { x <- normalize(mtcars, select = "mpg") - expect_equal( + expect_identical( unnormalize(x, select = "pg", regex = TRUE), unnormalize(x, select = "mpg") ) }) + + +test_that("unnormalize: grouped data", { + skip_if_not_installed("poorman") + + # 1 group, 1 normalized var + norm <- poorman::group_by(mtcars, cyl) + norm <- normalize(norm, "mpg") + expect_identical( + poorman::ungroup(unnormalize(norm, "mpg")), + mtcars, + ignore_attr = TRUE # unnormalize removed rownames + ) + + # 2 groups, 1 normalized var + set.seed(123) + test <- iris + test$grp <- sample(c("A", "B"), nrow(test), replace = TRUE) + norm <- poorman::group_by(test, Species, grp) + norm <- normalize(norm, "Sepal.Length") + expect_identical( + poorman::ungroup(unnormalize(norm, "Sepal.Length")), + test + ) + + # 2 groups, 2 normalized vars + set.seed(123) + test <- iris + test$grp <- sample(c("A", "B"), nrow(test), replace = TRUE) + norm <- poorman::group_by(test, Species, grp) + norm <- normalize(norm, c("Sepal.Length", "Petal.Length")) + unnorm <- unnormalize(norm, c("Sepal.Length", "Petal.Length")) + expect_identical( + poorman::ungroup(unnorm), + test + ) + + expect_s3_class(unnorm, "grouped_df") + + # can't recover attributes + norm <- poorman::group_by(iris, Species) + norm <- normalize(norm, "Sepal.Length") + attr(norm, "groups") <- NULL + + expect_error( + unnormalize(norm, "Sepal.Length"), + regexp = "Couldn't retrieve the necessary information" + ) + + # normalize applied on grouped data but unnormalize applied on ungrouped data + norm <- poorman::group_by(mtcars, cyl) + norm <- normalize(norm, "mpg") + norm <- poorman::ungroup(norm) + + expect_error( + unnormalize(norm, "mpg"), + regexp = "Can't unnormalize variable" + ) + + # normalize applied on grouped data but unnormalize applied different grouped + # data + norm <- poorman::group_by(norm, am) + expect_error( + unnormalize(norm, "mpg"), + regexp = "Couldn't retrieve the necessary" + ) + +})