【R】データの列および行を条件を指定して抽出する(filter、select)

こんてんつ

データフレームの条件に合う行、列だけ選択して抽出する方法を紹介します。tidyverseパッケージ集の中のdplyrパッケージのfilter関数、select関数を利用します。

早見チートシート

パッケージのインストール&読み込み

install.packages("tidyverse")
library(tidyverse)

行の選択

#数式の条件に合う行のみを抽出

iris %>%
  dplyr::filter(Sepal.Length > 7.5)

iris %>%
  dplyr::filter(Sepal.Length >= 6.7, Sepal.Length <= 7.0)

iris %>%
  dplyr::filter(Sepal.Length > 6.5, Petal.Length > 5.8)

iris %>%
  dplyr::filter(Sepal.Length > 6.5 & Petal.Length > 5.8)

#factor型などの文字列で指定した抽出

iris %>%
  dplyr::filter(Species == "setosa")

iris %>%
  dplyr::filter(Species == "setosa" | Species == "virginica")

iris %>%
  dplyr::filter(Species != "setosa", Species != "virginica")

列の選択

#列名で指定した抽出

iris %>% 
  select(Sepal.Length, Petal.Length)

iris %>% 
  select("Sepal.Length", "Petal.Length")

iris %>%
  select(Sepal.Width:Petal.Width)

#列番号で指定した抽出

iris %>%
  select(1,4)

iris %>%
  select(2:4)

#除外する場合

iris %>%
  select(-Sepal.Width, -Petal.Width)

#特定の文字列を含んだり、部分一致したりする列を抽出

iris %>%
  select(starts_with("Sepal"))

iris %>% 
  select(ends_with(("Width")))

iris %>%
  select(contains("Sepal"))

iris %>%
  select(-contains("Sepal"))

#character型ベクトルでの抽出

char_vec = c("Sepal.Length", "Petal.Length")
iris %>%
  select(all_of(char_vec))

char_vec = c("Sepal.Length", "Petal.Length")
iris %>%
  select(any_of(char_vec))

詳細

行の選択

数式条件の例。条件に合致した行を抽出。,&がANDを表す。|はORを表す。

iris %>%
  dplyr::filter(Sepal.Length > 6.5, Petal.Length > 5.8)

iris %>%
  dplyr::filter(Sepal.Length > 6.5 & Petal.Length > 5.8)

文字列による条件の例。条件に合致した行を抽出。,&がANDを表す。|はORを表す。

iris %>%
  dplyr::filter(Sepal.Width > 3.7, Species == "setosa" | Species == "virginica")

列の選択

列名で指定した例。

iris %>% 
  select(Sepal.Length, Petal.Length)

iris %>% 
  select("Sepal.Length", "Petal.Length")

列番号で指定した例。

iris %>%
  select(1,4)

:で範囲を指定した例。

iris %>%
  select(2:4)

-によって除外した例。

iris %>%
  select(-Sepal.Width, -Petal.Width)

starts_withで特定の文字列から始まるものを抽出した例。

iris %>%
  select(starts_with("Sepal"))

containsで特定の文字列を含むものを抽出した例。

iris %>%
  select(contains("Sepal"))

-containsで特定の文字列を含むものを除外した例。

iris %>%
  select(-contains("Sepal"))

character型ベクトルでの抽出の例。all_ofは一致しないものがあった場合エラーを返す。any_ofは一致しないものがあっても無視してプログラムを回す。

char_vec = c("Sepal.Length", "Petal.Length")
iris %>%
  select(all_of(char_vec))

char_vec = c("Sepal.Length", "Petal.Length")
iris %>%
  select(any_of(char_vec))