distinct: Select distinct/unique rows

Description Usage Arguments Examples

View source: R/distinct.R

Description

Retain only unique/distinct rows from an input tbl. This is similar to unique.data.frame(), but considerably faster.

Usage

1
distinct(.data, ..., .keep_all = FALSE)

Arguments

.data

a tbl

...

Optional variables to use when determining uniqueness. If there are multiple rows for a given combination of inputs, only the first row will be preserved. If omitted, will use all variables.

.keep_all

If TRUE, keep all variables in .data. If a combination of ... is not distinct, this keeps the first row of values.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
df <- tibble(
  x = sample(10, 100, rep = TRUE),
  y = sample(10, 100, rep = TRUE)
)
nrow(df)
nrow(distinct(df))
nrow(distinct(df, x, y))

distinct(df, x)
distinct(df, y)

# Can choose to keep all other variables as well
distinct(df, x, .keep_all = TRUE)
distinct(df, y, .keep_all = TRUE)

# You can also use distinct on computed variables
distinct(df, diff = abs(x - y))

# The same behaviour applies for grouped data frames
# except that the grouping variables are always included
df <- tibble(
  g = c(1, 1, 2, 2),
  x = c(1, 1, 2, 1)
) %>% group_by(g)
df %>% distinct()
df %>% distinct(x)

Example output

Attaching package: 'dplyr'

The following objects are masked from 'package:stats':

    filter, lag

The following objects are masked from 'package:base':

    intersect, setdiff, setequal, union

[1] 100
[1] 62
[1] 62
# A tibble: 10 x 1
       x
   <int>
 1     7
 2    10
 3     5
 4     1
 5     9
 6     2
 7     3
 8     6
 9     8
10     4
# A tibble: 10 x 1
       y
   <int>
 1     2
 2     3
 3     9
 4     6
 5     4
 6     7
 7    10
 8     5
 9     1
10     8
# A tibble: 10 x 2
       x     y
   <int> <int>
 1     7     2
 2    10     3
 3     5     6
 4     1     4
 5     9     2
 6     2    10
 7     3     7
 8     6     9
 9     8     7
10     4     7
# A tibble: 10 x 2
       x     y
   <int> <int>
 1     7     2
 2    10     3
 3    10     9
 4     5     6
 5     1     4
 6     5     7
 7     2    10
 8     1     5
 9    10     1
10     6     8
# A tibble: 10 x 1
    diff
   <int>
 1     5
 2     7
 3     1
 4     3
 5     2
 6     8
 7     4
 8     9
 9     0
10     6
Source: local data frame [2 x 1]
Groups: g [2]

# A tibble: 2 x 1
      g
  <dbl>
1     1
2     2
Source: local data frame [3 x 2]
Groups: g [2]

# A tibble: 3 x 2
      x     g
  <dbl> <dbl>
1     1     1
2     2     2
3     1     2

dplyr documentation built on Sept. 29, 2017, 1:03 a.m.