library(tidyverse)
rm(list = ls())
options(stringsAsFactors = T)
#基本用法不貼結(jié)果了哈
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行數(shù)據(jù)
mtcars %>% slice_min(mpg, n = 2)
mtcars %>% slice_max(mpg, n = 2)
# slice_min() 和 slice_max() 在極值有相同數(shù)值時會出現(xiàn)多行
# 如果要排除這種情況叮阅,可應(yīng)用with_ties = FALSE,會默認(rèn)第一次出現(xiàn)的結(jié)果
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)
# 依據(jù)數(shù)據(jù)中分類變量的比例進行抽取
mtcars$vs <- as.factor(mtcars$vs)
mtcars %>% slice_sample(weight_by = vs, n = 3)
mtcars %>% slice_sample(weight_by = vs, prop = 0.1)
代碼塊
代碼塊
代碼塊
代碼塊
代碼塊
代碼塊
代碼塊
代碼塊
代碼塊