I want to know how we can write similar to sapply in dplyr. Here I am calculating no. of distinct values. I have similar multiple sapply statements so I thought to write using mutate
in dplyr.
distinctValues <- sapply(iris, function(var) dplyr::n_distinct(var))
Update:
for different names you can use .names = "{.col}.new{.fn}"
iris %>%
summarize(across(everything(), n_distinct, .names = "{.col}.new{.fn}"))
We can use summarize
with across
library(dplyr)
iris %>%
summarize(across(everything(), n_distinct))
Output:
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 35 23 43 22 3
In base R
, we can do
sapply(iris, function(var) length(unique(var)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With