count_functions | R Documentation |
n_(...)
N_(...)
... |
< Columns to pick. You can't pick grouping columns because they are already automatically
handled by the verb (i.e. |
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()
A numeric vector representing the count from n
to N
.
Other Data Management:
append()
,
codebook()
,
cut()
,
tag_duplicates()
# 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()))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.