Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R dplyr - distinct accross all columns

Tags:

r

dplyr

Is there a way to specify dplyr::distinct should use all column names without resorting to nonstandard evaluation?

df <- data.frame(a=c(1,1,2),b=c(1,1,3))

df %>% distinct(a,b,.keep_all=FALSE)          # behavior I'd like to replicate

vs

df %>% distinct(everything(),.keep_all=FALSE) # with syntax of this form
like image 494
Sam Hart Avatar asked Mar 24 '16 00:03

Sam Hart


2 Answers

You can distinct the all columns with the code below.

library(dplyr)
library(data.table)

df <- data_frame(
  id = c(1, 1, 2, 2, 3, 3),
  value = c("a", "a", "b", "c", "d", "d")
)
# A tibble: 6 × 2
# id value
# <dbl> <chr>
# 1     1     a
# 2     1     a
# 3     2     b
# 4     2     c
# 5     3     d
# 6     3     d

# distinct with Non-Standard Evaluation
df %>% distinct()

# distinct with Standard Evaluation
df %>% distinct_()

# Also, you can set the column names with .dots.
df %>% distinct_(.dots = names(.))
# A tibble: 4 × 2
# id value
# <dbl> <chr>
# 1     1     a
# 2     2     b
# 3     2     c
# 4     3     d

# distinct with data.table
unique(as.data.table(df))
# id value
# 1:  1     a
# 2:  2     b
# 3:  2     c
# 4:  3     d
like image 120
Keiku Avatar answered Oct 14 '22 03:10

Keiku


As of version 1.0.5 of dplyr, the two following options yield the same output.

df <- data.frame(a = c(1, 1, 2),
                 b = c(1, 1, 3))

df %>% distinct(a, b)

  a b
1 1 1
2 2 3

df %>% distinct(across(everything()))

  a b
1 1 1
2 2 3

No reason to specify .keep_all = FALSE argument as this is the default.

You could also use tibble() instead of data.frame()

like image 23
Austin Avatar answered Oct 14 '22 04:10

Austin