dplyr 包中distinct() 函数与base 包中的unique() 函数比较类似,不同的是unique() 是一个泛型函数,可以针对向量、矩阵、数组、数据框甚至列表这五种数据类型,求取唯一值。而distinct() 函数则是专门为数据框设计的,这也与tidyverse 系列包的宗旨一致。
之前用distinct() 函数的时候,总容易出现问题,归根结底是没有弄明白distinct() 各参数的含义,囫囵吞枣的看了看文档,就开始写了。今天看到一篇很不错的博客,里面提到了distinct() 函数,感觉作者讲的很不错。 distinct() 用于对输入的tbl 进行去重,返回无重复的行,类似于base::unique() 。 函数,但是处理速度更快。原数据集行名称会被过滤掉。 语法:
1
| distinct(.data, ..., .keep_all = FALSE)
|
1 2 3 4 5 6
| df <- tibble::tibble( x = sample(10, 100, rep = TRUE), y = sample(10, 100, rep = TRUE) ) df
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #> # 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
|
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| # 以全部两个变量去重,返回去重后的行数 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)`结果一样 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去重,返回所有变量,相当于 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 # 对变量运算后的结果去重 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
|
|