dplyr包中distinct()函數(shù)與base包中的unique()函數(shù)比較類似,不同的是unique()是一個(gè)泛型函數(shù),可以針對向量、矩陣、數(shù)組、數(shù)據(jù)框甚至列表這五種數(shù)據(jù)類型,求取唯一值。而distinct()函數(shù)則是專門為數(shù)據(jù)框設(shè)計(jì)的,這也與tidyverse系列包的宗旨一致。
之前用distinct()函數(shù)的時(shí)候,總?cè)菀壮霈F(xiàn)問題,歸根結(jié)底是沒有弄明白distinct()各參數(shù)的含義,囫圇吞棗的看了看文檔,就開始寫了。今天看到一篇很不錯(cuò)的博客,里面提到了distinct()函數(shù),感覺作者講的很不錯(cuò)。
distinct()用于對輸入的tbl進(jìn)行去重,返回?zé)o重復(fù)的行,類似于base::unique()。
函數(shù),但是處理速度更快。原數(shù)據(jù)集行名稱會(huì)被過濾掉。
語法:
distinct(.data, ..., .keep_all = FALSE)
library(dplyr)
df <- tibble::tibble(
x = sample(10, 100, rep = TRUE),
y = sample(10, 100, rep = TRUE)
)
df
#> # A tibble: 100 x 2
#> x y
#> <int> <int>
#> 1 2 9
#> 2 6 7
#> 3 2 10
#> 4 6 9
#> 5 7 8
#> 6 10 1
#> 7 7 9
#> 8 9 9
#> 9 8 2
#> 10 3 1
#> # ... with 90 more rows
# 以全部兩個(gè)變量去重,返回去重后的行數(shù)
distinct(df)
#> # A tibble: 62 x 2
#> x y
#> <int> <int>
#> 1 2 9
#> 2 6 7
#> 3 2 10
#> 4 6 9
#> 5 7 8
#> 6 10 1
#> 7 7 9
#> 8 9 9
#> 9 8 2
#> 10 3 1
#> # ... with 52 more rows
# 和`distinct(df)`結(jié)果一樣
distinct(df, x, y)
#> # A tibble: 62 x 2
#> x y
#> <int> <int>
#> 1 2 9
#> 2 6 7
#> 3 2 10
#> 4 6 9
#> 5 7 8
#> 6 10 1
#> 7 7 9
#> 8 9 9
#> 9 8 2
#> 10 3 1
#> # ... with 52 more rows
# 以變量x去重,只返回去重后的x值
distinct(df, x)
#> # A tibble: 10 x 1
#> x
#> <int>
#> 1 2
#> 2 6
#> 3 7
#> 4 10
#> 5 9
#> 6 8
#> 7 3
#> 8 5
#> 9 4
#> 10 1
# 以變量y去重,只返回去重后的y值
distinct(df, y)
#> # A tibble: 10 x 1
#> y
#> <int>
#> 1 9
#> 2 7
#> 3 10
#> 4 8
#> 5 1
#> 6 2
#> 7 5
#> 8 6
#> 9 4
#> 10 3
# 以變量x去重,返回所有變量
distinct(df, x, .keep_all = TRUE)
#> # A tibble: 10 x 2
#> x y
#> <int> <int>
#> 1 2 9
#> 2 6 7
#> 3 7 8
#> 4 10 1
#> 5 9 9
#> 6 8 2
#> 7 3 1
#> 8 5 5
#> 9 4 4
#> 10 1 9
# 以變量y去重,返回所有變量,相當(dāng)于
distinct(df, y, .keep_all = TRUE)
#> # A tibble: 10 x 2
#> x y
#> <int> <int>
#> 1 2 9
#> 2 6 7
#> 3 2 10
#> 4 7 8
#> 5 10 1
#> 6 8 2
#> 7 7 5
#> 8 3 6
#> 9 8 4
#> 10 2 3
# 對變量運(yùn)算后的結(jié)果去重
distinct(df, diff = abs(x - y))
#> # A tibble: 10 x 1
#> diff
#> <int>
#> 1 7
#> 2 1
#> 3 8
#> 4 3
#> 5 9
#> 6 2
#> 7 0
#> 8 6
#> 9 5
#> 10 4