這些是從向量中提取單個值的有用幫助器。即使輸入比預期短,它們也保證返回有意義的值。您還可以提供一個可選的輔助向量來定義排序。
用法
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
中的缺失值?
細節
對於大多數向量類型, 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 dplyr ntile 將數值向量分為 n 組
- R dplyr nest_join 嵌套連接
- R dplyr n_distinct 計算獨特的組合
- R dplyr near 比較兩個數值向量
- R dplyr nest_by 由一個或多個變量嵌套
- R dplyr na_if 將值轉換為 NA
- R dplyr group_trim 修剪分組結構
- R dplyr slice 使用行的位置對行進行子集化
- R dplyr copy_to 將本地數據幀複製到遠程src
- R dplyr sample_n 從表中采樣 n 行
- R dplyr consecutive_id 為連續組合生成唯一標識符
- R dplyr row_number 整數排名函數
- R dplyr band_members 樂隊成員
- R dplyr mutate-joins 變異連接
- R dplyr coalesce 找到第一個非缺失元素
- R dplyr group_split 按組分割 DataFrame
- R dplyr mutate 創建、修改和刪除列
- R dplyr order_by 用於排序窗口函數輸出的輔助函數
- R dplyr context 有關“當前”組或變量的信息
- R dplyr percent_rank 比例排名函數
- R dplyr recode 重新編碼值
- R dplyr starwars 星球大戰人物
- R dplyr desc 降序
- R dplyr between 檢測值落在指定範圍內的位置
- R dplyr cumall 任何、全部和平均值的累積版本
注:本文由純淨天空篩選整理自Hadley Wickham等大神的英文原創作品 Extract the first, last, or nth value from a vector。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。