Skip to content

Commit

Permalink
allow n()
Browse files Browse the repository at this point in the history
  • Loading branch information
strengejacke committed Mar 4, 2024
1 parent 410090e commit da98164
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 1 deletion.
8 changes: 7 additions & 1 deletion R/data_modify.R
Original file line number Diff line number Diff line change
Expand Up @@ -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")) {
Expand Down
3 changes: 3 additions & 0 deletions R/data_summary.R
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
3 changes: 3 additions & 0 deletions man/data_summary.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions tests/testthat/test-data_summary.R
Original file line number Diff line number Diff line change
Expand Up @@ -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))
})

0 comments on commit da98164

Please sign in to comment.