library(tidyverse)
rm(list = ls())
options(stringsAsFactors = T)
#基本用法不贴结果了哈
data("mtcars")
mtcars %>% slice(1L)
# Similar to tail(mtcars, 1):
mtcars %>% slice(n())
mtcars %>% slice(5:n())
# Rows can be dropped with negative indices:
slice(mtcars, -(1:4))
# First and last rows based on existing order
mtcars %>% slice_head(n = 5)
mtcars %>% slice_tail(n = 5)
# 取mpg最大及最小的5行数据
mtcars %>% slice_min(mpg, n = 2)
mtcars %>% slice_max(mpg, n = 2)
# slice_min() 和 slice_max() 在极值有相同数值时会出现多行
# 如果要排除这种情况,可应用with_ties = FALSE,会默认第一次出现的结果
mtcars %>% slice_min(cyl, n = 1)
mtcars %>% slice_min(cyl, n = 1, with_ties = FALSE)
# 随机抽取行
mtcars %>% slice_sample(n = 5)
mtcars %>% slice_sample(n = 5, replace = TRUE)
# 依据数据中分类变量的比例进行抽取
mtcars$vs <- as.factor(mtcars$vs)
mtcars %>% slice_sample(weight_by = vs, n = 3)
mtcars %>% slice_sample(weight_by = vs, prop = 0.1)
代码块
代码块
代码块
代码块
代码块
代码块
代码块
代码块
代码块