見出し画像

まとめて列を選択: starts_with, ends_with

select() 関数で必要な列名を記述する際に、列が多すぎて、全てを列挙するのが難しいこともあります。そのときに、Sample1, Sample2 のように列の名前に規則性がある場合、便利な関数があります。

特定の文字で始まる列を選択: starts_with() 

starts_with() 関数を使うと、特定の文字で始まる列をまとめて指定することができます。"Sample" で始まる列であれば、 「starts_with("Sample")」と書けます。 

下記の例では、 result_data のテーブルから、 "Sample" で始まる列を指定して取り出し、 samples というオブジェクトに格納しています。

samples <- result_data %>% select(starts_with("Sample"))

> result_data
# A tibble: 3 x 5
  Id    Symbol Description   Sample1 Sample2
  <chr> <chr>  <chr>           <dbl>   <dbl>
1 id3   CCC    lorem ipsum c       3       6
2 id2   BBB    lorem ipsum b       2       5
3 id1   AAA    lorem ipsum a       1       4
>
>
> samples
# A tibble: 3 x 2
  Sample1 Sample2
    <dbl>   <dbl>
1       3       6
2       2       5
3       1       4

特定の文字で終わる列を選択: ends_with()

また、特定の文字で終わる列を選択する場合は、 "ends_with()" が使えます。
WT_1h, KO_1h, WT_12h, KO_12h のような列があったとき、 「select(ends_with("_1h"))」 と書けば、 WT_1h と KO_1h の列を選択して抽出することができます。

応用:除外する場合

前回、select() で列名を指定する場合に、「マイナス(-)列名」と記述できることを紹介しました。ここでも starts_with() と ends_with() を使うことができます。

result_data %>% select(-starts_with("Sample"))

このように書けば、"Sample" で始まる列を全て除外することができます。

*なお、select() の中で、選択と除外を同時に行うことができないことに注意してください。「select(Sample, -ends_with("1")」 のようには書けません。もし、複雑な条件で指定したい場合は、 いったん、選択したのち、除外するような書き方ならできます。

result_data %>% select(starts_with("Sample")) %>% select(-ends_with("_1"))


この記事が気に入ったらサポートをしてみませんか?