當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


R dplyr nth 從向量中提取第一個、最後一個或第 n 個值

這些是從向量中提取單個值的有用幫助器。即使輸入比預期短,它們也保證返回有意義的值。您還可以提供一個可選的輔助向量來定義排序。

用法

nth(x, n, order_by = NULL, default = NULL, na_rm = FALSE)

first(x, order_by = NULL, default = NULL, na_rm = FALSE)

last(x, order_by = NULL, default = NULL, na_rm = FALSE)

參數

x

一個向量

n

對於 nth() ,指定位置的單個整數。負整數從末尾開始索引(即 -1L 將返回向量中的最後一個值)。

order_by

x 大小相同的可選向量,用於確定順序。

default

如果 x 中不存在該位置,則使用默認值。

如果是 NULL (默認值),則使用缺失值。

如果提供,則它必須是單個值,該值將被轉換為 x 的類型。

x為列表時,default允許為任意值。在這種情況下沒有類型或尺寸限製。

na_rm

在提取值之前是否應該刪除 x 中的缺失值?

如果 x 是一個列表,則為該列表中的單個元素。否則,與 x 類型相同、大小為 1 的向量。

細節

對於大多數向量類型, first(x)last(x)nth(x, n) 的工作方式分別類似於 x[[1]]x[[length(x)]x[[n]] 。主要的例外是數據幀,它們在其中檢索行,即 x[1, ]x[nrow(x), ]x[n, ] 。這與 tidyverse/vctrs 原則一致,該原則將數據幀視為行向量,而不是列向量。

例子

x <- 1:10
y <- 10:1

first(x)
#> [1] 1
last(y)
#> [1] 1

nth(x, 1)
#> [1] 1
nth(x, 5)
#> [1] 5
nth(x, -2)
#> [1] 9

# `first()` and `last()` are often useful in `summarise()`
df <- tibble(x = x, y = y)
df %>%
  summarise(
    across(x:y, first, .names = "{col}_first"),
    y_last = last(y)
  )
#> # A tibble: 1 × 3
#>   x_first y_first y_last
#>     <int>   <int>  <int>
#> 1       1      10      1

# Selecting a position that is out of bounds returns a default value
nth(x, 11)
#> [1] NA
nth(x, 0)
#> [1] NA

# This out of bounds behavior also applies to empty vectors
first(integer())
#> [1] NA

# You can customize the default value with `default`
nth(x, 11, default = -1L)
#> [1] -1
first(integer(), default = 0L)
#> [1] 0

# `order_by` provides optional ordering
last(x)
#> [1] 10
last(x, order_by = y)
#> [1] 1

# `na_rm` removes missing values before extracting the value
z <- c(NA, NA, 1, 3, NA, 5, NA)
first(z)
#> [1] NA
first(z, na_rm = TRUE)
#> [1] 1
last(z, na_rm = TRUE)
#> [1] 5
nth(z, 3, na_rm = TRUE)
#> [1] 5

# For data frames, these select entire rows
df <- tibble(a = 1:5, b = 6:10)
first(df)
#> # A tibble: 1 × 2
#>       a     b
#>   <int> <int>
#> 1     1     6
nth(df, 4)
#> # A tibble: 1 × 2
#>       a     b
#>   <int> <int>
#> 1     4     9
源代碼:R/nth-value.R

相關用法


注:本文由純淨天空篩選整理自Hadley Wickham等大神的英文原創作品 Extract the first, last, or nth value from a vector。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。