添字

概要

dplyrパッケージに含まれるnth(), first(), last()は、添字の値を取得する関数です。主にsummarise()と併せて使用します。

関連ページ

関数

nth(x, n, order_by = NULL, default = default_missing(x))
first(x, order_by = NULL, default = default_missing(x))
last(x, order_by = NULL, default = default_missing(x))
引数指定説明
x必須対象の列を指定する
n必須nth()で使用する
取得する値の番号(添字)を指定する
order_by任意並べ替える列を指定する
default任意存在しない値の代替値を指定する

使い方

解説用データフレーム

df <- tibble(
  x1 = c(2, 1, 3)
)
> df
# A tibble: 3 x 1
     x1
  <dbl>
1     2
2     1
3     3

1.添字を指定して値を取得する

1-1.先頭の値を取得する

以下のコードは、全て同じ結果を返します。

# nth()を使用する例
summarise(df, y1 = nth(x1, n = 1))

# first()を使用する例
summarise(df, y1 = first(x1))
# A tibble: 1 x 1
     y1
  <dbl>
1     2

1-2.末尾の値を取得する

以下のコードは、全て同じ結果を返します。

# nth()を使用する例
summarise(df, y1 = nth(x1, n = -1))

# last()を使用する例
summarise(df, y1 = last(x1))
# A tibble: 1 x 1
     y1
  <dbl>
1     3

1-3.任意の値を取得する

# 列x1の2番目の値を取得する
summarise(df, y1 = nth(x1, n = 2))
# A tibble: 1 x 1
     y1
  <dbl>
1     1

2.オプション

2-1.並べ替え

# 列x1を基準に並べ替え、列x1の1番目の値を取得する
summarise(df, y1 = nth(x1, n = 1, order_by = x1))
# A tibble: 1 x 1
     y1
  <dbl>
1     1

1-2.末尾の値を取得する

以下のコードは、全て同じ結果を返します。

# 列x1に4番目の値が存在しないため、代替値の0を返す
summarise(df, y1 = nth(x1, n = 4, default = 0))
# A tibble: 1 x 1
     y1
  <dbl>
1     0
Sponsored Link