Nhiều trường hợp chúng ta cần lọc ra những rows là các giá trị ranking thứ nth trong các nhóm.
Chọn giá trị nhỏ nhất, lớn nhất thì tương đối dễ dàng hơn chọn những giá trị có ranking thứ n bất kì (nth).
Chúng ta lấy dataset iris để minh họa
library(tidyverse)
Registered S3 methods overwritten by 'dbplyr':
method from
print.tbl_lazy
print.tbl_sql
-- Attaching packages ------------------------------ tidyverse 1.3.1 --
v ggplot2 3.3.5 v purrr 0.3.4
v tibble 3.1.4 v dplyr 1.0.7
v tidyr 1.1.4 v stringr 1.4.0
v readr 2.0.2 v forcats 0.5.1
-- Conflicts --------------------------------- tidyverse_conflicts() --
x dplyr::filter() masks stats::filter()
x dplyr::lag() masks stats::lag()
library(data.table)
Registered S3 method overwritten by 'data.table':
method from
print.data.table
data.table 1.14.2 using 4 threads (see ?getDTthreads). Latest news: r-datatable.com
Attaching package: ‘data.table’
The following objects are masked from ‘package:dplyr’:
between, first, last
The following object is masked from ‘package:purrr’:
transpose
data("iris")
Chọn các row có giá trị Sepal.Length lớn nhất
iris.max <- setDT(iris)[, .SD[which.max(Sepal.Length)], by = Species] # Max of groups
head(iris.max)
Chọn các row có giá trị Sepal.Length nhỏ nhất
iris.min <- setDT(iris)[, .SD[which.min(Sepal.Length)], by = Species] # Min of groups
head(iris.min)
Sử dụng dplyr. Sau khi sorting và ranking những rows trong các nhóm, chúng ta chọn rows thứ n = 10 trong mỗi nhóm.3 nhóm Species chọn ra 3 rows có rank = 10 như sau
iris.n <- iris # Replicate example data
iris.n <- iris.n %>% arrange(Species, desc(Sepal.Length)) %>%
group_by(Species) %>%
mutate(numbering = row_number()) %>% # Create numbering variable
filter(numbering == 10)
iris.n
Hoặc cách khác
library(dplyr)
iris.nth <- iris %>% arrange(Species, desc(Sepal.Length)) %>%
group_by(Species) %>%
mutate(rank = sequence(rle(as.character(iris$Species))$lengths)) %>%
filter(rank == 10)
head(iris.nth)
NA