Difference between Distinct vs Unique

Viewed 22905

What are the differences between distinct and unique in R using dplyr in consideration to:

  • Speed
  • Capabilities (valid inputs, parameters, etc) & Uses
  • Output

For example:

library(dplyr)
data(iris)

# creating data with duplicates
iris_dup <- bind_rows(iris, iris)

d <- distinct(iris_dup)
u <- unique(iris_dup)

all(d==u) # returns True

In this example distinct and unique perform the same function. Are there examples of times you should use one but not the other? Are there any tricks or common uses of one?

2 Answers

With regard to two of your criteria, speed and input, here's a little function using the tictoc library. It shows that distinct() is notably faster (the input has numeric and character columns):

library(dplyr)
library(tictoc)
library(glue)

make_a_df <- function(nrows = NULL){
  tic()
  df <- tibble(
    alpha = sample(letters, nrows, replace = TRUE),
    numeric = rnorm(mean = 0, sd = 1, n = nrows)
  )
  unique(df)
  print(glue('Unique with {nrows}: '))
  toc()

  tic()
  df <- tibble(
    alpha = sample(letters, nrows, replace = TRUE),
    numeric = rnorm(mean = 0, sd = 1, n = nrows)
  )
  distinct(df)
  print(glue('Distinct with {nrows}: '))
  toc()
}

Result:

> make_a_df(50); make_a_df(500); make_a_df(5000); make_a_df(50000); make_a_df(500000)
Unique with 50: 
0.02 sec elapsed
Distinct with 50: 
0 sec elapsed
Unique with 500: 
0 sec elapsed
Distinct with 500: 
0 sec elapsed
Unique with 5000: 
0.02 sec elapsed
Distinct with 5000: 
0 sec elapsed
Unique with 50000: 
0.09 sec elapsed
Distinct with 50000: 
0.01 sec elapsed
Unique with 5e+05: 
1.77 sec elapsed
Distinct with 5e+05: 
0.34 sec elapsed
Related