From da981646c10e303dec81e15bd92c989a94a7deb9 Mon Sep 17 00:00:00 2001 From: Daniel Date: Mon, 4 Mar 2024 08:22:49 +0100 Subject: [PATCH] allow n() --- R/data_modify.R | 8 +++++++- R/data_summary.R | 3 +++ man/data_summary.Rd | 3 +++ tests/testthat/test-data_summary.R | 8 ++++++++ 4 files changed, 21 insertions(+), 1 deletion(-) diff --git a/R/data_modify.R b/R/data_modify.R index 6234255fd..bf85ff045 100644 --- a/R/data_modify.R +++ b/R/data_modify.R @@ -350,7 +350,13 @@ data_modify.grouped_df <- function(data, ..., .if = NULL, .at = NULL, .modify = } # finally, we can evaluate expression and get values for new variables - new_variable <- try(with(data, eval(symbol)), silent = TRUE) + new_variable <- switch( + insight::safe_deparse(symbol), + # "special" functions + "n()" = nrow(data), + # default evaluation of expression + try(with(data, eval(symbol)), silent = TRUE) + ) # successful, or any errors, like misspelled variable name? if (inherits(new_variable, "try-error")) { diff --git a/R/data_summary.R b/R/data_summary.R index 90f3e8ae3..65540da88 100644 --- a/R/data_summary.R +++ b/R/data_summary.R @@ -38,6 +38,9 @@ #' #' # expressions can also be supplied as character strings #' data_summary(mtcars, "MW = mean(mpg)", "SD = sd(mpg)", by = c("am", "gear")) +#' +#' # count observations within groups +#' data_summary(mtcars, observations = n(), by = c("am", "gear")) #' @export data_summary <- function(x, ...) { UseMethod("data_summary") diff --git a/man/data_summary.Rd b/man/data_summary.Rd index 0602dc7da..01fefae8c 100644 --- a/man/data_summary.Rd +++ b/man/data_summary.Rd @@ -52,4 +52,7 @@ data_summary(mtcars, MW = mean(mpg), SD = sd(mpg), by = c("am", "gear")) # expressions can also be supplied as character strings data_summary(mtcars, "MW = mean(mpg)", "SD = sd(mpg)", by = c("am", "gear")) + +# count observations within groups +data_summary(mtcars, observations = n(), by = c("am", "gear")) } diff --git a/tests/testthat/test-data_summary.R b/tests/testthat/test-data_summary.R index aede5c042..2f7fd3308 100644 --- a/tests/testthat/test-data_summary.R +++ b/tests/testthat/test-data_summary.R @@ -200,3 +200,11 @@ test_that("data_summary, expression as variable", { expect_named(out, c("am", "gear", "MW", "SD")) expect_equal(out$SD, aggregate(mtcars["mpg"], list(mtcars$am, mtcars$gear), sd)$mpg, tolerance = 1e-4) }) + + +test_that("data_summary, extra functions", { + data(mtcars) + # n() + out <- data_summary(mtcars, n = n(), by = c("am", "gear")) + expect_identical(out$n, c(15L, 4L, 8L, 5L)) +})