Alternative to Sapply in dplyr

Viewed 201

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))
4 Answers

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)))

You can also use the following solution:

library(purrr)

iris %>%
  map_dbl(~ n_distinct(.x))

Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
          35           23           43           22            3 

A data.table option using uniqueN

> as.data.table(iris)[, sapply(.SD, uniqueN)]
Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
          35           23           43           22            3
Related