count_functions: Count from n to N

count_functionsR Documentation

Count from n to N

Description

\Sexpr[results=rd]{lifecycle::badge("stable")}

Usage

n_(...)

N_(...)

Arguments

...

<tidy-select>

Columns to pick.

You can't pick grouping columns because they are already automatically handled by the verb (i.e. summarise() or mutate()).

Details

These functions are used for indexing observations or generating sequences of numbers.

  • n_() generates a running counter within a group of variables and represents the number of the current observation.

  • N_() provides the total count within each group of variables.

You can do these operations using dplyr::n() in this way. See examples below using iris dataset.

iris |> mutate(.N_ = n()) |> head() iris |> mutate(.n_ = 1:n()) |> head() iris |> group_by(Species) |> mutate(.n_ = 1:n()) |> slice(1:5) |> ungroup()

Value

A numeric vector representing the count from n to N.

See Also

Other Data Management: append(), codebook(), cut(), tag_duplicates()

Examples


# Example with a custom dataset
df <- data.frame(
  x = c(1, 1, 2, 2, 2, 3, 4, 4, 4, 4),
  y = letters[1:10]
)

library(dplyr)

# Generate a running counter for each observation within the "x" group using mutate()
mutate(df, n = n_(x))

# Generate a running counter for each observation for all columns using mutate()
mutate(df, n = n_(everything()))

# Generate the total count of observations using summarise()
reframe(df, n = n_(x))

# Generate the total count of observations within the "x" group using summarise()
mutate(df, N = N_(everything()))
mutate(df, N = N_(x))
reframe(df, N = N_(x))

# iris dataset
mutate(iris, n = n_(everything()))
mutate(iris, N = N_(everything()))

myominnoo/mStats documentation built on Nov. 29, 2023, 2:36 a.m.