6

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

4 Answers 4

8

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
1
  • Thank you. Is there any way we can label them differently? May 16, 2021 at 16:59
4

In base R, we can do

sapply(iris, function(var) length(unique(var)))
4

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 
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
1
  • sapply(iris, uniqueN) is simpler and does the same.
    – andschar
    Sep 2, 2021 at 7:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.