分享

dplyr包中的distinct()函数

 脑系科数据科学 2020-04-15

dplyr包中distinct()函数与base包中的unique()函数比较类似,不同的是unique()是一个泛型函数,可以针对向量、矩阵、数组、数据框甚至列表这五种数据类型,求取唯一值。而distinct()函数则是专门为数据框设计的,这也与tidyverse系列包的宗旨一致。

之前用distinct()函数的时候,总容易出现问题,归根结底是没有弄明白distinct()各参数的含义,囫囵吞枣的看了看文档,就开始写了。今天看到一篇很不错的博客,里面提到了distinct()函数,感觉作者讲的很不错。

distinct()用于对输入的tbl进行去重,返回无重复的行,类似于base::unique()
函数,但是处理速度更快。原数据集行名称会被过滤掉。
语法:

1

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

1

library(dplyr)

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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约