6.8 数据去重
单个数值型向量去重,此时和 unique 函数作用一样
(x <- c(9:20, 1:5, 3:7, 0:8))## [1] 9 10 11 12 13 14 15 16 17 18 19 20 1 2 3 4 5 3 4 5 6 7 0 1 2
## [26] 3 4 5 6 7 8
## extract unique elements
x[!duplicated(x)]## [1] 9 10 11 12 13 14 15 16 17 18 19 20 1 2 3 4 5 6 7 0 8
unique(x)## [1] 9 10 11 12 13 14 15 16 17 18 19 20 1 2 3 4 5 6 7 0 8
数据框类型数据中,去除重复的行,这个重复可以是多个变量对应的向量
set.seed(2019)
df <- data.frame(
x = sample(0:1, 10, replace = T),
y = sample(0:1, 10, replace = T),
z = 1:10
)
df## x y z
## 1 0 0 1
## 2 0 1 2
## 3 1 0 3
## 4 0 0 4
## 5 0 1 5
## 6 0 1 6
## 7 1 0 7
## 8 0 1 8
## 9 0 0 9
## 10 1 0 10
df[!duplicated(df[, c("x", "y")]), ]## x y z
## 1 0 0 1
## 2 0 1 2
## 3 1 0 3
去掉字段 cyl 和 gear 有重复的记录,data.table 方式
mtcars_df[!duplicated(mtcars_df, by = c("cyl", "gear"))][,.(mpg, cyl, gear)]## mpg cyl gear
## 1: 21.0 6 4
## 2: 22.8 4 4
## 3: 21.4 6 3
## 4: 18.7 8 3
## 5: 21.5 4 3
## 6: 26.0 4 5
## 7: 15.8 8 5
## 8: 19.7 6 5
dplyr 方式
mtcars |>
dplyr::distinct(cyl, gear, .keep_all = TRUE) |>
dplyr::select(mpg, cyl, gear)## mpg cyl gear
## Mazda RX4 21.0 6 4
## Datsun 710 22.8 4 4
## Hornet 4 Drive 21.4 6 3
## Hornet Sportabout 18.7 8 3
## Toyota Corona 21.5 4 3
## Porsche 914-2 26.0 4 5
## Ford Pantera L 15.8 8 5
## Ferrari Dino 19.7 6 5
dplyr 的去重操作不需要拷贝一个新的数据对象 mtcars_df,并且可以以管道的方式将后续的选择操作连接起来,代码更加具有可读性。
mtcars_df[!duplicated(mtcars_df[, c("cyl", "gear")]), c("mpg","cyl","gear")]## mpg cyl gear
## 1: 21.0 6 4
## 2: 22.8 4 4
## 3: 21.4 6 3
## 4: 18.7 8 3
## 5: 21.5 4 3
## 6: 26.0 4 5
## 7: 15.8 8 5
## 8: 19.7 6 5
Base R 和 data.table 提供的 duplicated() 函数和 [ 函数一起实现去重的操作,选择操作放在 [ 实现,[ 其实是一个函数
x <- 2:4
x[1]## [1] 2
`[`(x, 1)## [1] 2